From 31eb619ea18d05e004da853d70b165ba47291c92 Mon Sep 17 00:00:00 2001
From: Anmizi <1845513904@qq.com>
Date: Fri, 29 Apr 2022 19:15:41 +0800
Subject: [PATCH 001/162] =?UTF-8?q?=E4=BC=98=E5=8C=96JS=E7=89=88=E6=9C=AC?=
=?UTF-8?q?=E4=BB=A3=E7=A0=81=20(0039.=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8C?=
=?UTF-8?q?.md)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0039.组合总和.md | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md
index 98b37b84..e10a827f 100644
--- a/problems/0039.组合总和.md
+++ b/problems/0039.组合总和.md
@@ -370,18 +370,17 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int)
```js
var combinationSum = function(candidates, target) {
const res = [], path = [];
- candidates.sort(); // 排序
+ candidates.sort((a,b)=>a-b); // 排序
backtracking(0, 0);
return res;
function backtracking(j, sum) {
- if (sum > target) return;
if (sum === target) {
res.push(Array.from(path));
return;
}
for(let i = j; i < candidates.length; i++ ) {
const n = candidates[i];
- if(n > target - sum) continue;
+ if(n > target - sum) break;
path.push(n);
sum += n;
backtracking(i, sum);
From 5b3607c6a151b6fd6dd548c1b26f3f1fb8514047 Mon Sep 17 00:00:00 2001
From: Anmizi <1845513904@qq.com>
Date: Fri, 29 Apr 2022 23:18:33 +0800
Subject: [PATCH 002/162] =?UTF-8?q?=E4=BF=AE=E6=94=B9=200040.=E7=BB=84?=
=?UTF-8?q?=E5=90=88=E6=80=BB=E5=92=8CII.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0040.组合总和II.md | 15 ++++++++++-----
1 file changed, 10 insertions(+), 5 deletions(-)
diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md
index de13e031..34ac64e6 100644
--- a/problems/0040.组合总和II.md
+++ b/problems/0040.组合总和II.md
@@ -508,22 +508,27 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int)
*/
var combinationSum2 = function(candidates, target) {
const res = []; path = [], len = candidates.length;
- candidates.sort();
+ candidates.sort((a,b)=>a-b);
backtracking(0, 0);
return res;
function backtracking(sum, i) {
- if (sum > target) return;
if (sum === target) {
res.push(Array.from(path));
return;
}
- let f = -1;
for(let j = i; j < len; j++) {
const n = candidates[j];
- if(n > target - sum || n === f) continue;
+ if(j > i && candidates[j] === candidates[j-1]){
+ //若当前元素和前一个元素相等
+ //则本次循环结束,防止出现重复组合
+ continue;
+ }
+ //如果当前元素值大于目标值-总和的值
+ //由于数组已排序,那么该元素之后的元素必定不满足条件
+ //直接终止当前层的递归
+ if(n > target - sum) break;
path.push(n);
sum += n;
- f = n;
backtracking(sum, j + 1);
path.pop();
sum -= n;
From 55c78be1280054615f23c9e5859d139a7f840705 Mon Sep 17 00:00:00 2001
From: dmzlingyin
Date: Fri, 29 Apr 2022 23:38:34 +0800
Subject: [PATCH 003/162] =?UTF-8?q?update=20(0739.=E6=AF=8F=E6=97=A5?=
=?UTF-8?q?=E6=B8=A9=E5=BA=A6.md):=20python=E4=BB=A3=E7=A0=81=E9=AB=98?=
=?UTF-8?q?=E4=BA=AE?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0739.每日温度.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md
index 710f5eb6..7deab0a3 100644
--- a/problems/0739.每日温度.md
+++ b/problems/0739.每日温度.md
@@ -233,7 +233,7 @@ class Solution {
}
```
Python:
-``` Python3
+```python
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
answer = [0]*len(temperatures)
From d0a79760b65a1078284b036be6dcf8fa8eec5076 Mon Sep 17 00:00:00 2001
From: dmzlingyin
Date: Fri, 29 Apr 2022 23:41:26 +0800
Subject: [PATCH 004/162] =?UTF-8?q?update=20(0739.=E6=AF=8F=E6=97=A5?=
=?UTF-8?q?=E6=B8=A9=E5=BA=A6.md):=20=E8=AF=AD=E8=A8=80=E8=A1=A8=E8=BF=B0?=
=?UTF-8?q?=E4=BF=AE=E5=A4=8D?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0739.每日温度.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md
index 7deab0a3..f0f782d2 100644
--- a/problems/0739.每日温度.md
+++ b/problems/0739.每日温度.md
@@ -34,7 +34,7 @@
那么单调栈的原理是什么呢?为什么时间复杂度是O(n)就可以找到每一个元素的右边第一个比它大的元素位置呢?
-单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素的元素,优点是只需要遍历一次。
+单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素大的元素,优点是只需要遍历一次。
在使用单调栈的时候首先要明确如下几点:
From 636550d44c4ac65521865cca00b1c3c8b9f7c756 Mon Sep 17 00:00:00 2001
From: dmzlingyin
Date: Fri, 29 Apr 2022 23:50:31 +0800
Subject: [PATCH 005/162] =?UTF-8?q?update=20(0739.=E6=AF=8F=E6=97=A5?=
=?UTF-8?q?=E6=B8=A9=E5=BA=A6.md):=20=E5=A2=9E=E5=8A=A0=E6=9C=AA=E7=B2=BE?=
=?UTF-8?q?=E7=AE=80=E7=89=88=E6=9C=ACGo=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0739.每日温度.md | 30 +++++++++++++++++++++++++++++-
1 file changed, 29 insertions(+), 1 deletion(-)
diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md
index f0f782d2..206bebd2 100644
--- a/problems/0739.每日温度.md
+++ b/problems/0739.每日温度.md
@@ -277,8 +277,36 @@ func dailyTemperatures(t []int) []int {
}
```
-> 单调栈法
+> 单调栈法(未精简版本)
+```go
+func dailyTemperatures(temperatures []int) []int {
+ res := make([]int, len(temperatures))
+ // 初始化栈顶元素为第一个下标索引0
+ stack := []int{0}
+
+ for i := 1; i < len(temperatures); i++ {
+ top := stack[len(stack)-1]
+ if temperatures[i] < temperatures[top] {
+ stack = append(stack, i)
+ } else if temperatures[i] == temperatures[top] {
+ stack = append(stack, i)
+ } else {
+ for len(stack) != 0 && temperatures[i] > temperatures[top] {
+ res[top] = i - top
+ stack = stack[:len(stack)-1]
+ if len(stack) != 0 {
+ top = stack[len(stack)-1]
+ }
+ }
+ stack = append(stack, i)
+ }
+ }
+ return res
+}
+```
+
+> 单调栈法(精简版本)
```go
// 单调递减栈
func dailyTemperatures(num []int) []int {
From 49ec574821f687ea8703c61245f815bf2dc76139 Mon Sep 17 00:00:00 2001
From: dmzlingyin
Date: Sat, 30 Apr 2022 11:04:17 +0800
Subject: [PATCH 006/162] =?UTF-8?q?update=20(0496.=E4=B8=8B=E4=B8=80?=
=?UTF-8?q?=E4=B8=AA=E6=9B=B4=E5=A4=A7=E5=85=83=E7=B4=A0I):=20=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0=E6=9C=AA=E7=B2=BE=E7=AE=80Go=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0496.下一个更大元素I.md | 33 ++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/problems/0496.下一个更大元素I.md b/problems/0496.下一个更大元素I.md
index f9dfa308..02339677 100644
--- a/problems/0496.下一个更大元素I.md
+++ b/problems/0496.下一个更大元素I.md
@@ -244,6 +244,39 @@ class Solution:
```
Go:
+
+> 未精简版本
+```go
+func nextGreaterElement(nums1 []int, nums2 []int) []int {
+ res := make([]int, len(nums1))
+ for i := range res { res[i] = -1 }
+ m := make(map[int]int, len(nums1))
+ for k, v := range nums1 { m[v] = k }
+
+ stack := []int{0}
+ for i := 1; i < len(nums2); i++ {
+ top := stack[len(stack)-1]
+ if nums2[i] < nums2[top] {
+ stack = append(stack, i)
+ } else if nums2[i] == nums2[top] {
+ stack = append(stack, i)
+ } else {
+ for len(stack) != 0 && nums2[i] > nums2[top] {
+ if v, ok := m[nums2[top]]; ok {
+ res[v] = nums2[i]
+ }
+ stack = stack[:len(stack)-1]
+ if len(stack) != 0 {
+ top = stack[len(stack)-1]
+ }
+ }
+ stack = append(stack, i)
+ }
+ }
+ return res
+}
+```
+> 精简版本
```go
func nextGreaterElement(nums1 []int, nums2 []int) []int {
res := make([]int, len(nums1))
From 82e8b9eaac23041c2a358af126ec4e268ee383fa Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sat, 30 Apr 2022 21:18:55 +0800
Subject: [PATCH 007/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880509.?=
=?UTF-8?q?=E6=96=90=E6=B3=A2=E9=82=A3=E5=A5=91=E6=95=B0.md=EF=BC=89?=
=?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0509.斐波那契数.md | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md
index d339940c..1d17784d 100644
--- a/problems/0509.斐波那契数.md
+++ b/problems/0509.斐波那契数.md
@@ -245,7 +245,29 @@ var fib = function(n) {
};
```
+TypeScript
+
+```typescript
+function fib(n: number): number {
+ /**
+ dp[i]: 第i个斐波那契数
+ dp[0]: 0;
+ dp[1]:1;
+ ...
+ dp[i] = dp[i - 1] + dp[i - 2];
+ */
+ const dp: number[] = [];
+ dp[0] = 0;
+ dp[1] = 1;
+ for (let i = 2; i <= n; i++) {
+ dp[i] = dp[i - 1] + dp[i - 2];
+ }
+ return dp[n];
+};
+```
+
### C
+
动态规划:
```c
int fib(int n){
From 0cba2d22f2d032bbf478662ef622d8022af24f21 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sat, 30 Apr 2022 21:53:14 +0800
Subject: [PATCH 008/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880070.?=
=?UTF-8?q?=E7=88=AC=E6=A5=BC=E6=A2=AF.md=EF=BC=89=EF=BC=9A=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0070.爬楼梯.md | 51 +++++++++++++++++++++++++++++++++++++++++
1 file changed, 51 insertions(+)
diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md
index da19ea0e..34d41441 100644
--- a/problems/0070.爬楼梯.md
+++ b/problems/0070.爬楼梯.md
@@ -308,7 +308,58 @@ var climbStairs = function(n) {
};
```
+TypeScript
+
+> 爬2阶
+
+```typescript
+function climbStairs(n: number): number {
+ /**
+ dp[i]: i阶楼梯的方法种数
+ dp[1]: 1;
+ dp[2]: 2;
+ ...
+ dp[i]: dp[i - 1] + dp[i - 2];
+ */
+ const dp: number[] = [];
+ dp[1] = 1;
+ dp[2] = 2;
+ for (let i = 3; i <= n; i++) {
+ dp[i] = dp[i - 1] + dp[i - 2];
+ }
+ return dp[n];
+};
+```
+
+> 爬m阶
+
+```typescript
+function climbStairs(n: number): number {
+ /**
+ 一次可以爬m阶
+ dp[i]: i阶楼梯的方法种数
+ dp[1]: 1;
+ dp[2]: 2;
+ dp[3]: dp[2] + dp[1];
+ ...
+ dp[i]: dp[i - 1] + dp[i - 2] + ... + dp[max(i - m, 1)]; 从i-1加到max(i-m, 1)
+ */
+ const m: number = 2; // 本题m为2
+ const dp: number[] = new Array(n + 1).fill(0);
+ dp[1] = 1;
+ dp[2] = 2;
+ for (let i = 3; i <= n; i++) {
+ const end: number = Math.max(i - m, 1);
+ for (let j = i - 1; j >= end; j--) {
+ dp[i] += dp[j];
+ }
+ }
+ return dp[n];
+};
+```
+
### C
+
```c
int climbStairs(int n){
//若n<=2,返回n
From 1e81ef27100c8fc76bc38ec0135a4b18554398af Mon Sep 17 00:00:00 2001
From: Beim <73528776+162-jld@users.noreply.github.com>
Date: Sun, 1 May 2022 11:51:11 +0800
Subject: [PATCH 009/162] =?UTF-8?q?Update=200383.=E8=B5=8E=E9=87=91?=
=?UTF-8?q?=E4=BF=A1.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0383.赎金信.md | 28 +++++++++++++++-------------
1 file changed, 15 insertions(+), 13 deletions(-)
diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md
index 00707347..56dcb8dd 100644
--- a/problems/0383.赎金信.md
+++ b/problems/0383.赎金信.md
@@ -110,23 +110,25 @@ Java:
```Java
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
- //记录杂志字符串出现的次数
- int[] arr = new int[26];
- int temp;
- for (int i = 0; i < magazine.length(); i++) {
- temp = magazine.charAt(i) - 'a';
- arr[temp]++;
+ // 定义一个哈希映射数组
+ int[] record = new int[26];
+
+ // 遍历
+ for(char c : magazine.toCharArray()){
+ record[c - 'a'] += 1;
}
- for (int i = 0; i < ransomNote.length(); i++) {
- temp = ransomNote.charAt(i) - 'a';
- //对于金信中的每一个字符都在数组中查找
- //找到相应位减一,否则找不到返回false
- if (arr[temp] > 0) {
- arr[temp]--;
- } else {
+
+ for(char c : ransomNote.toCharArray()){
+ record[c - 'a'] -= 1;
+ }
+
+ // 如果数组中存在负数,说明ransomNote字符串总存在magazine中没有的字符
+ for(int i : record){
+ if(i < 0){
return false;
}
}
+
return true;
}
}
From 25e26f1f86bf246f93560710f41dcf5a26414770 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sun, 1 May 2022 13:45:25 +0800
Subject: [PATCH 010/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0(0746.=E4=BD=BF?=
=?UTF-8?q?=E7=94=A8=E6=9C=80=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC?=
=?UTF-8?q?=E6=A2=AF.md)=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0746.使用最小花费爬楼梯.md | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md
index c356955a..5931fc8a 100644
--- a/problems/0746.使用最小花费爬楼梯.md
+++ b/problems/0746.使用最小花费爬楼梯.md
@@ -266,7 +266,30 @@ var minCostClimbingStairs = function(cost) {
};
```
+### TypeScript
+
+```typescript
+function minCostClimbingStairs(cost: number[]): number {
+ /**
+ dp[i]: 走到第i阶需要花费的最少金钱
+ dp[0]: cost[0];
+ dp[1]: cost[1];
+ ...
+ dp[i]: min(dp[i - 1], dp[i - 2]) + cost[i];
+ */
+ const dp: number[] = [];
+ const length: number = cost.length;
+ dp[0] = cost[0];
+ dp[1] = cost[1];
+ for (let i = 2; i <= length; i++) {
+ dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
+ }
+ return Math.min(dp[length - 1], dp[length - 2]);
+};
+```
+
### C
+
```c
int minCostClimbingStairs(int* cost, int costSize){
//开辟dp数组,大小为costSize
From fc28660b6189b010709bedc7dd5acf678eaf47ed Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sun, 1 May 2022 14:42:12 +0800
Subject: [PATCH 011/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880062.?=
=?UTF-8?q?=E4=B8=8D=E5=90=8C=E8=B7=AF=E5=BE=84.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0062.不同路径.md | 30 +++++++++++++++++++++++++++++-
1 file changed, 29 insertions(+), 1 deletion(-)
diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md
index 4a9af129..f59b7be8 100644
--- a/problems/0062.不同路径.md
+++ b/problems/0062.不同路径.md
@@ -273,7 +273,7 @@ public:
return dp[m-1][n-1];
}
-```
+```
### Python
```python
@@ -347,7 +347,35 @@ var uniquePaths = function(m, n) {
};
```
+### TypeScript
+
+```typescript
+function uniquePaths(m: number, n: number): number {
+ /**
+ dp[i][j]: 到达(i, j)的路径数
+ dp[0][*]: 1;
+ dp[*][0]: 1;
+ ...
+ dp[i][j]: dp[i - 1][j] + dp[i][j - 1];
+ */
+ const dp: number[][] = new Array(m).fill(0).map(_ => []);
+ for (let i = 0; i < m; i++) {
+ dp[i][0] = 1;
+ }
+ for (let i = 0; i < n; i++) {
+ dp[0][i] = 1;
+ }
+ for (let i = 1; i < m; i++) {
+ for (let j = 1; j < n; j++) {
+ dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
+ }
+ }
+ return dp[m - 1][n - 1];
+};
+```
+
### C
+
```c
//初始化dp数组
int **initDP(int m, int n) {
From 8c596b161a140a76ea57130ac61a009308bd277c Mon Sep 17 00:00:00 2001
From: Beim <1497359184@qq.com>
Date: Sun, 1 May 2022 15:45:58 +0800
Subject: [PATCH 012/162] modify_problems_0383
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 1d7f219d..3d44ca69 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@
-# LeetCode 刷题攻略
+# LeetCode 刷题攻略1111
## 刷题攻略的背景
@@ -254,7 +254,7 @@
33. [二叉树:构造一棵搜索树](./problems/0108.将有序数组转换为二叉搜索树.md)
34. [二叉树:搜索树转成累加树](./problems/0538.把二叉搜索树转换为累加树.md)
35. [二叉树:总结篇!(需要掌握的二叉树技能都在这里了)](./problems/二叉树总结篇.md)
-
+
## 回溯算法
题目分类大纲如下:
From d3e1f1d3b3406f28e7494340928fbc1866c0b6f6 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sun, 1 May 2022 19:24:05 +0800
Subject: [PATCH 013/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880063.?=
=?UTF-8?q?=E4=B8=8D=E5=90=8C=E8=B7=AF=E5=BE=84II.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0063.不同路径II.md | 33 ++++++++++++++++++++++++++++++++-
1 file changed, 32 insertions(+), 1 deletion(-)
diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md
index a40cceda..d09ea0e6 100644
--- a/problems/0063.不同路径II.md
+++ b/problems/0063.不同路径II.md
@@ -352,7 +352,38 @@ var uniquePathsWithObstacles = function(obstacleGrid) {
};
```
-C
+### TypeScript
+
+```typescript
+function uniquePathsWithObstacles(obstacleGrid: number[][]): number {
+ /**
+ dp[i][j]: 到达(i, j)的路径数
+ dp[0][*]: 用u表示第一个障碍物下标,则u之前为1,u之后(含u)为0
+ dp[*][0]: 同上
+ ...
+ dp[i][j]: obstacleGrid[i][j] === 1 ? 0 : dp[i-1][j] + dp[i][j-1];
+ */
+ const m: number = obstacleGrid.length;
+ const n: number = obstacleGrid[0].length;
+ const dp: number[][] = new Array(m).fill(0).map(_ => new Array(n).fill(0));
+ for (let i = 0; i < m && obstacleGrid[i][0] === 0; i++) {
+ dp[i][0] = 1;
+ }
+ for (let i = 0; i < n && obstacleGrid[0][i] === 0; i++) {
+ dp[0][i] = 1;
+ }
+ for (let i = 1; i < m; i++) {
+ for (let j = 1; j < n; j++) {
+ if (obstacleGrid[i][j] === 1) continue;
+ dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
+ }
+ }
+ return dp[m - 1][n - 1];
+};
+```
+
+### C
+
```c
//初始化dp数组
int **initDP(int m, int n, int** obstacleGrid) {
From dd514eb08787dd203cea4668f75477971b4e88fe Mon Sep 17 00:00:00 2001
From: wang <472146630@qq.com>
Date: Sun, 1 May 2022 21:08:57 +0800
Subject: [PATCH 014/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200053.=E6=9C=80?=
=?UTF-8?q?=E5=A4=A7=E5=AD=90=E5=BA=8F=E5=92=8C=E3=80=810135=E5=88=86?=
=?UTF-8?q?=E5=8F=91=E7=B3=96=E6=9E=9C=E5=92=8C0455=E5=88=86=E5=8F=91?=
=?UTF-8?q?=E9=A5=BC=E5=B9=B2=E7=9A=84=20Rust=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0053.最大子序和.md | 20 +++++++++++++++++---
problems/0135.分发糖果.md | 29 ++++++++++++++++++++++++-----
problems/0455.分发饼干.md | 36 ++++++++++++++++++++++++++++--------
3 files changed, 69 insertions(+), 16 deletions(-)
diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md
index b5fb7642..9dbc7313 100644
--- a/problems/0053.最大子序和.md
+++ b/problems/0053.最大子序和.md
@@ -140,7 +140,7 @@ public:
## 其他语言版本
-### Java
+### Java
```java
class Solution {
public int maxSubArray(int[] nums) {
@@ -180,7 +180,7 @@ class Solution {
}
```
-### Python
+### Python
```python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
@@ -195,7 +195,7 @@ class Solution:
return result
```
-### Go
+### Go
```go
func maxSubArray(nums []int) int {
@@ -212,6 +212,20 @@ func maxSubArray(nums []int) int {
}
```
+### Rust
+```rust
+pub fn max_sub_array(nums: Vec) -> i32 {
+ let mut max_sum = i32::MIN;
+ let mut curr = 0;
+ for n in nums.iter() {
+ curr += n;
+ max_sum = max_sum.max(curr);
+ curr = curr.max(0);
+ }
+ max_sum
+}
+```
+
### Javascript:
```Javascript
var maxSubArray = function(nums) {
diff --git a/problems/0135.分发糖果.md b/problems/0135.分发糖果.md
index ccdabc16..ce738689 100644
--- a/problems/0135.分发糖果.md
+++ b/problems/0135.分发糖果.md
@@ -126,11 +126,11 @@ public:
## 其他语言版本
-### Java
+### Java
```java
class Solution {
- /**
- 分两个阶段
+ /**
+ 分两个阶段
1、起点下标1 从左往右,只要 右边 比 左边 大,右边的糖果=左边 + 1
2、起点下标 ratings.length - 2 从右往左, 只要左边 比 右边 大,此时 左边的糖果应该 取本身的糖果数(符合比它左边大) 和 右边糖果数 + 1 二者的最大值,这样才符合 它比它左边的大,也比它右边大
*/
@@ -160,7 +160,7 @@ class Solution {
}
```
-### Python
+### Python
```python
class Solution:
def candy(self, ratings: List[int]) -> int:
@@ -213,6 +213,25 @@ func findMax(num1 int ,num2 int) int{
}
```
+### Rust
+```rust
+pub fn candy(ratings: Vec) -> i32 {
+ let mut candies = vec![1i32; ratings.len()];
+ for i in 1..ratings.len() {
+ if ratings[i - 1] < ratings[i] {
+ candies[i] = candies[i - 1] + 1;
+ }
+ }
+
+ for i in (0..ratings.len()-1).rev() {
+ if ratings[i] > ratings[i + 1] {
+ candies[i] = candies[i].max(candies[i + 1] + 1);
+ }
+ }
+ candies.iter().sum()
+}
+```
+
### Javascript:
```Javascript
var candy = function(ratings) {
@@ -229,7 +248,7 @@ var candy = function(ratings) {
candys[i] = Math.max(candys[i], candys[i + 1] + 1)
}
}
-
+
let count = candys.reduce((a, b) => {
return a + b
})
diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md
index d95a407a..17db4a85 100644
--- a/problems/0455.分发饼干.md
+++ b/problems/0455.分发饼干.md
@@ -106,7 +106,7 @@ public:
## 其他语言版本
-### Java
+### Java
```java
class Solution {
// 思路1:优先考虑饼干,小饼干先喂饱小胃口
@@ -145,7 +145,7 @@ class Solution {
}
```
-### Python
+### Python
```python
class Solution:
# 思路1:优先考虑胃饼干
@@ -166,13 +166,13 @@ class Solution:
s.sort()
start, count = len(s) - 1, 0
for index in range(len(g) - 1, -1, -1): # 先喂饱大胃口
- if start >= 0 and g[index] <= s[start]:
+ if start >= 0 and g[index] <= s[start]:
start -= 1
count += 1
return count
```
-### Go
+### Go
```golang
//排序后,局部最优
func findContentChildren(g []int, s []int) int {
@@ -191,7 +191,27 @@ func findContentChildren(g []int, s []int) int {
}
```
-### Javascript
+### Rust
+```rust
+pub fn find_content_children(children: Vec, cookie: Vec) -> i32 {
+ let mut children = children;
+ let mut cookies = cookie;
+ children.sort();
+ cookies.sort();
+
+ let (mut child, mut cookie) = (0usize, 0usize);
+ while child < children.len() && cookie < cookies.len() {
+ // 优先选择最小饼干喂饱孩子
+ if children[child] <= cookies[cookie] {
+ child += 1;
+ }
+ cookie += 1
+ }
+ child as i32
+}
+```
+
+### Javascript
```js
var findContentChildren = function(g, s) {
g = g.sort((a, b) => a - b)
@@ -203,7 +223,7 @@ var findContentChildren = function(g, s) {
result++
index--
}
- }
+ }
return result
};
@@ -251,7 +271,7 @@ function findContentChildren(g: number[], s: number[]): number {
};
```
-### C
+### C
```c
int cmp(int* a, int* b) {
@@ -261,7 +281,7 @@ int cmp(int* a, int* b) {
int findContentChildren(int* g, int gSize, int* s, int sSize){
if(sSize == 0)
return 0;
-
+
//将两个数组排序为升序
qsort(g, gSize, sizeof(int), cmp);
qsort(s, sSize, sizeof(int), cmp);
From 4c03ad7a78fcb324da45e97a2cfca618af1086c8 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sun, 1 May 2022 22:32:12 +0800
Subject: [PATCH 015/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880343.?=
=?UTF-8?q?=E6=95=B4=E6=95=B0=E6=8B=86=E5=88=86.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0343.整数拆分.md | 28 +++++++++++++++++++++++++++-
1 file changed, 27 insertions(+), 1 deletion(-)
diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md
index 4a7ba6ab..279f1d71 100644
--- a/problems/0343.整数拆分.md
+++ b/problems/0343.整数拆分.md
@@ -274,7 +274,33 @@ var integerBreak = function(n) {
};
```
-C:
+### TypeScript
+
+```typescript
+function integerBreak(n: number): number {
+ /**
+ dp[i]: i对应的最大乘积
+ dp[2]: 1;
+ ...
+ dp[i]: max(
+ 1 * dp[i - 1], 1 * (i - 1),
+ 2 * dp[i - 2], 2 * (i - 2),
+ ..., (i - 2) * dp[2], (i - 2) * 2
+ );
+ */
+ const dp: number[] = new Array(n + 1).fill(0);
+ dp[2] = 1;
+ for (let i = 3; i <= n; i++) {
+ for (let j = 1; j <= i - 2; j++) {
+ dp[i] = Math.max(dp[i], j * dp[i - j], j * (i - j));
+ }
+ }
+ return dp[n];
+};
+```
+
+### C
+
```c
//初始化DP数组
int *initDP(int num) {
From b1ef364ffb9c0082f401c34bdd6bf22c4f330fa5 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Mon, 2 May 2022 17:25:45 +0800
Subject: [PATCH 016/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880096.?=
=?UTF-8?q?=E4=B8=8D=E5=90=8C=E7=9A=84=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2?=
=?UTF-8?q?=E6=A0=91.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0096.不同的二叉搜索树.md | 28 +++++++++++++++++++++++++++-
1 file changed, 27 insertions(+), 1 deletion(-)
diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md
index 41fcb8fe..25561b50 100644
--- a/problems/0096.不同的二叉搜索树.md
+++ b/problems/0096.不同的二叉搜索树.md
@@ -227,7 +227,33 @@ const numTrees =(n) => {
};
```
-C:
+TypeScript
+
+```typescript
+function numTrees(n: number): number {
+ /**
+ dp[i]: i个节点对应的种树
+ dp[0]: -1; 无意义;
+ dp[1]: 1;
+ ...
+ dp[i]: 2 * dp[i - 1] +
+ (dp[1] * dp[i - 2] + dp[2] * dp[i - 3] + ... + dp[i - 2] * dp[1]); 从1加到i-2
+ */
+ const dp: number[] = [];
+ dp[0] = -1; // 表示无意义
+ dp[1] = 1;
+ for (let i = 2; i <= n; i++) {
+ dp[i] = 2 * dp[i - 1];
+ for (let j = 1, end = i - 1; j < end; j++) {
+ dp[i] += dp[j] * dp[end - j];
+ }
+ }
+ return dp[n];
+};
+```
+
+### C
+
```c
//开辟dp数组
int *initDP(int n) {
From 5440c3d46b16565a265e30e498662829bf40b5e1 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Tue, 3 May 2022 11:48:03 +0800
Subject: [PATCH 017/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E8=83=8C?=
=?UTF-8?q?=E5=8C=85=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C?=
=?UTF-8?q?=E5=8C=85-1.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/背包理论基础01背包-1.md | 42 ++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md
index fe940b4c..257e87e4 100644
--- a/problems/背包理论基础01背包-1.md
+++ b/problems/背包理论基础01背包-1.md
@@ -423,5 +423,47 @@ function test () {
test();
```
+### TypeScript
+
+```typescript
+function testWeightBagProblem(
+ weight: number[],
+ value: number[],
+ size: number
+): number {
+ /**
+ * dp[i][j]: 前i个物品,背包容量为j,能获得的最大价值
+ * dp[0][*]: u=weight[0],u之前为0,u之后(含u)为value[0]
+ * dp[*][0]: 0
+ * ...
+ * dp[i][j]: max(dp[i-1][j], dp[i-1][j-weight[i]]+value[i]);
+ */
+ const goodsNum: number = weight.length;
+ const dp: number[][] = new Array(goodsNum)
+ .fill(0)
+ .map((_) => new Array(size + 1).fill(0));
+ for (let i = weight[0]; i <= size; i++) {
+ dp[0][i] = value[0];
+ }
+ for (let i = 1; i < goodsNum; i++) {
+ for (let j = 1; j <= size; j++) {
+ if (j < weight[i]) {
+ dp[i][j] = dp[i - 1][j];
+ } else {
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
+ }
+ }
+ }
+ return dp[goodsNum - 1][size];
+}
+// test
+const weight = [1, 3, 4];
+const value = [15, 20, 30];
+const size = 4;
+console.log(testWeightBagProblem(weight, value, size));
+```
+
+
+
-----------------------
From 36f630b109a93685bb241884e5584b327028d5f5 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Tue, 3 May 2022 12:34:20 +0800
Subject: [PATCH 018/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E8=83=8C?=
=?UTF-8?q?=E5=8C=85=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C?=
=?UTF-8?q?=E5=8C=85-2.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/背包理论基础01背包-2.md | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md
index dabdfb2d..bb5e3a03 100644
--- a/problems/背包理论基础01背包-2.md
+++ b/problems/背包理论基础01背包-2.md
@@ -315,6 +315,30 @@ function test () {
test();
```
+### TypeScript
+
+```typescript
+function testWeightBagProblem(
+ weight: number[],
+ value: number[],
+ size: number
+): number {
+ const goodsNum: number = weight.length;
+ const dp: number[] = new Array(size + 1).fill(0);
+ for (let i = 0; i < goodsNum; i++) {
+ for (let j = size; j >= weight[i]; j--) {
+ dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]);
+ }
+ }
+ return dp[size];
+}
+const weight = [1, 3, 4];
+const value = [15, 20, 30];
+const size = 4;
+console.log(testWeightBagProblem(weight, value, size));
+
+```
+
-----------------------
From a38ee5f525af998683a2d0fb38f6c6cac1312f5d Mon Sep 17 00:00:00 2001
From: Frankheartusf <104822497+Frankheartusf@users.noreply.github.com>
Date: Tue, 3 May 2022 17:31:37 +0800
Subject: [PATCH 019/162] Add files via upload
---
0045.跳跃游戏II.md | 287 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 287 insertions(+)
create mode 100644 0045.跳跃游戏II.md
diff --git a/0045.跳跃游戏II.md b/0045.跳跃游戏II.md
new file mode 100644
index 00000000..c0d3c3e5
--- /dev/null
+++ b/0045.跳跃游戏II.md
@@ -0,0 +1,287 @@
+
+
+
+
+
参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!
+
+
+> 相对于[贪心算法:跳跃游戏](https://mp.weixin.qq.com/s/606_N9j8ACKCODoCbV1lSA)难了不少,做好心里准备!
+
+# 45.跳跃游戏II
+
+[力扣题目链接](https://leetcode-cn.com/problems/jump-game-ii/)
+
+给定一个非负整数数组,你最初位于数组的第一个位置。
+
+数组中的每个元素代表你在该位置可以跳跃的最大长度。
+
+你的目标是使用最少的跳跃次数到达数组的最后一个位置。
+
+示例:
+* 输入: [2,3,1,1,4]
+* 输出: 2
+* 解释: 跳到最后一个位置的最小跳跃数是 2。从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
+
+说明:
+假设你总是可以到达数组的最后一个位置。
+
+
+## 思路
+
+本题相对于[55.跳跃游戏](https://programmercarl.com/0055.跳跃游戏.html)还是难了不少。
+
+但思路是相似的,还是要看最大覆盖范围。
+
+本题要计算最小步数,那么就要想清楚什么时候步数才一定要加一呢?
+
+贪心的思路,局部最优:当前可移动距离尽可能多走,如果还没到终点,步数再加一。整体最优:一步尽可能多走,从而达到最小步数。
+
+思路虽然是这样,但在写代码的时候还不能真的就能跳多远跳远,那样就不知道下一步最远能跳到哪里了。
+
+**所以真正解题的时候,要从覆盖范围出发,不管怎么跳,覆盖范围内一定是可以跳到的,以最小的步数增加覆盖范围,覆盖范围一旦覆盖了终点,得到的就是最小步数!**
+
+**这里需要统计两个覆盖范围,当前这一步的最大覆盖和下一步最大覆盖**。
+
+如果移动下标达到了当前这一步的最大覆盖最远距离了,还没有到终点的话,那么就必须再走一步来增加覆盖范围,直到覆盖范围覆盖了终点。
+
+如图:
+
+
+
+**图中覆盖范围的意义在于,只要红色的区域,最多两步一定可以到!(不用管具体怎么跳,反正一定可以跳到)**
+
+## 方法一
+
+从图中可以看出来,就是移动下标达到了当前覆盖的最远距离下标时,步数就要加一,来增加覆盖距离。最后的步数就是最少步数。
+
+这里还是有个特殊情况需要考虑,当移动下标达到了当前覆盖的最远距离下标时
+
+* 如果当前覆盖最远距离下标不是是集合终点,步数就加一,还需要继续走。
+* 如果当前覆盖最远距离下标就是是集合终点,步数不用加一,因为不能再往后走了。
+
+C++代码如下:(详细注释)
+
+```CPP
+// 版本一
+class Solution {
+public:
+ int jump(vector& nums) {
+ if (nums.size() == 1) return 0;
+ int curDistance = 0; // 当前覆盖最远距离下标
+ int ans = 0; // 记录走的最大步数
+ int nextDistance = 0; // 下一步覆盖最远距离下标
+ for (int i = 0; i < nums.size(); i++) {
+ nextDistance = max(nums[i] + i, nextDistance); // 更新下一步覆盖最远距离下标
+ if (i == curDistance) { // 遇到当前覆盖最远距离下标
+ if (curDistance != nums.size() - 1) { // 如果当前覆盖最远距离下标不是终点
+ ans++; // 需要走下一步
+ curDistance = nextDistance; // 更新当前覆盖最远距离下标(相当于加油了)
+ if (nextDistance >= nums.size() - 1) break; // 下一步的覆盖范围已经可以达到终点,结束循环
+ } else break; // 当前覆盖最远距离下标是集合终点,不用做ans++操作了,直接结束
+ }
+ }
+ return ans;
+ }
+};
+```
+
+## 方法二
+
+依然是贪心,思路和方法一差不多,代码可以简洁一些。
+
+**针对于方法一的特殊情况,可以统一处理**,即:移动下标只要遇到当前覆盖最远距离的下标,直接步数加一,不考虑是不是终点的情况。
+
+想要达到这样的效果,只要让移动下标,最大只能移动到nums.size - 2的地方就可以了。
+
+因为当移动下标指向nums.size - 2时:
+
+* 如果移动下标等于当前覆盖最大距离下标, 需要再走一步(即ans++),因为最后一步一定是可以到的终点。(题目假设总是可以到达数组的最后一个位置),如图:
+
+
+* 如果移动下标不等于当前覆盖最大距离下标,说明当前覆盖最远距离就可以直接达到终点了,不需要再走一步。如图:
+
+
+
+代码如下:
+
+```CPP
+// 版本二
+class Solution {
+public:
+ int jump(vector& nums) {
+ int curDistance = 0; // 当前覆盖的最远距离下标
+ int ans = 0; // 记录走的最大步数
+ int nextDistance = 0; // 下一步覆盖的最远距离下标
+ for (int i = 0; i < nums.size() - 1; i++) { // 注意这里是小于nums.size() - 1,这是关键所在
+ nextDistance = max(nums[i] + i, nextDistance); // 更新下一步覆盖的最远距离下标
+ if (i == curDistance) { // 遇到当前覆盖的最远距离下标
+ curDistance = nextDistance; // 更新当前覆盖的最远距离下标
+ ans++;
+ }
+ }
+ return ans;
+ }
+};
+```
+
+可以看出版本二的代码相对于版本一简化了不少!
+
+其精髓在于控制移动下标i只移动到nums.size() - 2的位置,所以移动下标只要遇到当前覆盖最远距离的下标,直接步数加一,不用考虑别的了。
+
+## 总结
+
+相信大家可以发现,这道题目相当于[55.跳跃游戏](https://programmercarl.com/0055.跳跃游戏.html)难了不止一点。
+
+但代码又十分简单,贪心就是这么巧妙。
+
+理解本题的关键在于:**以最小的步数增加最大的覆盖范围,直到覆盖范围覆盖了终点**,这个范围内最小步数一定可以跳到,不用管具体是怎么跳的,不纠结于一步究竟跳一个单位还是两个单位。
+
+
+## 其他语言版本
+
+
+### Java
+```Java
+// 版本一
+class Solution {
+ public int jump(int[] nums) {
+ if (nums == null || nums.length == 0 || nums.length == 1) {
+ return 0;
+ }
+ //记录跳跃的次数
+ int count=0;
+ //当前的覆盖最大区域
+ int curDistance = 0;
+ //最大的覆盖区域
+ int maxDistance = 0;
+ for (int i = 0; i < nums.length; i++) {
+ //在可覆盖区域内更新最大的覆盖区域
+ maxDistance = Math.max(maxDistance,i+nums[i]);
+ //说明当前一步,再跳一步就到达了末尾
+ if (maxDistance>=nums.length-1){
+ count++;
+ break;
+ }
+ //走到当前覆盖的最大区域时,更新下一步可达的最大区域
+ if (i==curDistance){
+ curDistance = maxDistance;
+ count++;
+ }
+ }
+ return count;
+ }
+}
+```
+
+```java
+// 版本二
+class Solution {
+ public int jump(int[] nums) {
+ int result = 0;
+ // 当前覆盖的最远距离下标
+ int end = 0;
+ // 下一步覆盖的最远距离下标
+ int temp = 0;
+ for (int i = 0; i <= end && end < nums.length - 1; ++i) {
+ temp = Math.max(temp, i + nums[i]);
+ // 可达位置的改变次数就是跳跃次数
+ if (i == end) {
+ end = temp;
+ result++;
+ }
+ }
+ return result;
+ }
+}
+```
+
+### Python
+
+```python
+class Solution:
+ def jump(self, nums: List[int]) -> int:
+ if len(nums) == 1: return 0
+ ans = 0
+ curDistance = 0
+ nextDistance = 0
+ for i in range(len(nums)):
+ nextDistance = max(i + nums[i], nextDistance)
+ if i == curDistance:
+ if curDistance != len(nums) - 1:
+ ans += 1
+ curDistance = nextDistance
+ if nextDistance >= len(nums) - 1: break
+ return ans
+```
+
+### Go
+```Go
+func jump(nums []int) int {
+ dp := make([]int, len(nums))
+ dp[0] = 0//初始第一格跳跃数一定为0
+
+ for i := 1; i < len(nums); i++ {
+ dp[i] = i
+ for j := 0; j < i; j++ {
+ if nums[j] + j >= i {//nums[j]为起点,j为往右跳的覆盖范围,这行表示从j能跳到i
+ dp[i] = min(dp[j] + 1, dp[i])//更新最小能到i的跳跃次数
+ }
+ }
+ }
+ return dp[len(nums)-1]
+}
+
+func min(a, b int) int {
+ if a < b {
+ return a
+ } else {
+ return b
+ }
+}
+```
+
+### Javascript
+```Javascript
+var jump = function(nums) {
+ let curIndex = 0
+ let nextIndex = 0
+ let steps = 0
+ for(let i = 0; i < nums.length - 1; i++) {
+ nextIndex = Math.max(nums[i] + i, nextIndex)
+ if(i === curIndex) {
+ curIndex = nextIndex
+ steps++
+ }
+ }
+
+ return steps
+};
+```
+
+### TypeScript
+
+```typescript
+function jump(nums: number[]): number {
+ const length: number = nums.length;
+ let curFarthestIndex: number = 0,
+ nextFarthestIndex: number = 0;
+ let curIndex: number = 0;
+ let stepNum: number = 0;
+ while (curIndex < length - 1) {
+ nextFarthestIndex = Math.max(nextFarthestIndex, curIndex + nums[curIndex]);
+ if (curIndex === curFarthestIndex) {
+ curFarthestIndex = nextFarthestIndex;
+ stepNum++;
+ }
+ curIndex++;
+ }
+ return stepNum;
+};
+```
+
+
+
+
+
+-----------------------
+
From 64d477e3f05c2b7ebb8aa3b5b8ed27578b5a1b31 Mon Sep 17 00:00:00 2001
From: Frankheartusf <2332517004@qq.com>
Date: Tue, 3 May 2022 17:50:07 +0800
Subject: [PATCH 020/162] =?UTF-8?q?=E4=BF=AE=E6=94=B9=200045=20=E8=B7=B3?=
=?UTF-8?q?=E8=B7=83=E9=97=AE=E9=A2=98II=20golang=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
0045.跳跃游戏II.md | 287 ------------------------------------
problems/0045.跳跃游戏II.md | 30 ++--
2 files changed, 19 insertions(+), 298 deletions(-)
delete mode 100644 0045.跳跃游戏II.md
diff --git a/0045.跳跃游戏II.md b/0045.跳跃游戏II.md
deleted file mode 100644
index c0d3c3e5..00000000
--- a/0045.跳跃游戏II.md
+++ /dev/null
@@ -1,287 +0,0 @@
-
-
-
-
-
参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!
-
-
-> 相对于[贪心算法:跳跃游戏](https://mp.weixin.qq.com/s/606_N9j8ACKCODoCbV1lSA)难了不少,做好心里准备!
-
-# 45.跳跃游戏II
-
-[力扣题目链接](https://leetcode-cn.com/problems/jump-game-ii/)
-
-给定一个非负整数数组,你最初位于数组的第一个位置。
-
-数组中的每个元素代表你在该位置可以跳跃的最大长度。
-
-你的目标是使用最少的跳跃次数到达数组的最后一个位置。
-
-示例:
-* 输入: [2,3,1,1,4]
-* 输出: 2
-* 解释: 跳到最后一个位置的最小跳跃数是 2。从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
-
-说明:
-假设你总是可以到达数组的最后一个位置。
-
-
-## 思路
-
-本题相对于[55.跳跃游戏](https://programmercarl.com/0055.跳跃游戏.html)还是难了不少。
-
-但思路是相似的,还是要看最大覆盖范围。
-
-本题要计算最小步数,那么就要想清楚什么时候步数才一定要加一呢?
-
-贪心的思路,局部最优:当前可移动距离尽可能多走,如果还没到终点,步数再加一。整体最优:一步尽可能多走,从而达到最小步数。
-
-思路虽然是这样,但在写代码的时候还不能真的就能跳多远跳远,那样就不知道下一步最远能跳到哪里了。
-
-**所以真正解题的时候,要从覆盖范围出发,不管怎么跳,覆盖范围内一定是可以跳到的,以最小的步数增加覆盖范围,覆盖范围一旦覆盖了终点,得到的就是最小步数!**
-
-**这里需要统计两个覆盖范围,当前这一步的最大覆盖和下一步最大覆盖**。
-
-如果移动下标达到了当前这一步的最大覆盖最远距离了,还没有到终点的话,那么就必须再走一步来增加覆盖范围,直到覆盖范围覆盖了终点。
-
-如图:
-
-
-
-**图中覆盖范围的意义在于,只要红色的区域,最多两步一定可以到!(不用管具体怎么跳,反正一定可以跳到)**
-
-## 方法一
-
-从图中可以看出来,就是移动下标达到了当前覆盖的最远距离下标时,步数就要加一,来增加覆盖距离。最后的步数就是最少步数。
-
-这里还是有个特殊情况需要考虑,当移动下标达到了当前覆盖的最远距离下标时
-
-* 如果当前覆盖最远距离下标不是是集合终点,步数就加一,还需要继续走。
-* 如果当前覆盖最远距离下标就是是集合终点,步数不用加一,因为不能再往后走了。
-
-C++代码如下:(详细注释)
-
-```CPP
-// 版本一
-class Solution {
-public:
- int jump(vector& nums) {
- if (nums.size() == 1) return 0;
- int curDistance = 0; // 当前覆盖最远距离下标
- int ans = 0; // 记录走的最大步数
- int nextDistance = 0; // 下一步覆盖最远距离下标
- for (int i = 0; i < nums.size(); i++) {
- nextDistance = max(nums[i] + i, nextDistance); // 更新下一步覆盖最远距离下标
- if (i == curDistance) { // 遇到当前覆盖最远距离下标
- if (curDistance != nums.size() - 1) { // 如果当前覆盖最远距离下标不是终点
- ans++; // 需要走下一步
- curDistance = nextDistance; // 更新当前覆盖最远距离下标(相当于加油了)
- if (nextDistance >= nums.size() - 1) break; // 下一步的覆盖范围已经可以达到终点,结束循环
- } else break; // 当前覆盖最远距离下标是集合终点,不用做ans++操作了,直接结束
- }
- }
- return ans;
- }
-};
-```
-
-## 方法二
-
-依然是贪心,思路和方法一差不多,代码可以简洁一些。
-
-**针对于方法一的特殊情况,可以统一处理**,即:移动下标只要遇到当前覆盖最远距离的下标,直接步数加一,不考虑是不是终点的情况。
-
-想要达到这样的效果,只要让移动下标,最大只能移动到nums.size - 2的地方就可以了。
-
-因为当移动下标指向nums.size - 2时:
-
-* 如果移动下标等于当前覆盖最大距离下标, 需要再走一步(即ans++),因为最后一步一定是可以到的终点。(题目假设总是可以到达数组的最后一个位置),如图:
-
-
-* 如果移动下标不等于当前覆盖最大距离下标,说明当前覆盖最远距离就可以直接达到终点了,不需要再走一步。如图:
-
-
-
-代码如下:
-
-```CPP
-// 版本二
-class Solution {
-public:
- int jump(vector& nums) {
- int curDistance = 0; // 当前覆盖的最远距离下标
- int ans = 0; // 记录走的最大步数
- int nextDistance = 0; // 下一步覆盖的最远距离下标
- for (int i = 0; i < nums.size() - 1; i++) { // 注意这里是小于nums.size() - 1,这是关键所在
- nextDistance = max(nums[i] + i, nextDistance); // 更新下一步覆盖的最远距离下标
- if (i == curDistance) { // 遇到当前覆盖的最远距离下标
- curDistance = nextDistance; // 更新当前覆盖的最远距离下标
- ans++;
- }
- }
- return ans;
- }
-};
-```
-
-可以看出版本二的代码相对于版本一简化了不少!
-
-其精髓在于控制移动下标i只移动到nums.size() - 2的位置,所以移动下标只要遇到当前覆盖最远距离的下标,直接步数加一,不用考虑别的了。
-
-## 总结
-
-相信大家可以发现,这道题目相当于[55.跳跃游戏](https://programmercarl.com/0055.跳跃游戏.html)难了不止一点。
-
-但代码又十分简单,贪心就是这么巧妙。
-
-理解本题的关键在于:**以最小的步数增加最大的覆盖范围,直到覆盖范围覆盖了终点**,这个范围内最小步数一定可以跳到,不用管具体是怎么跳的,不纠结于一步究竟跳一个单位还是两个单位。
-
-
-## 其他语言版本
-
-
-### Java
-```Java
-// 版本一
-class Solution {
- public int jump(int[] nums) {
- if (nums == null || nums.length == 0 || nums.length == 1) {
- return 0;
- }
- //记录跳跃的次数
- int count=0;
- //当前的覆盖最大区域
- int curDistance = 0;
- //最大的覆盖区域
- int maxDistance = 0;
- for (int i = 0; i < nums.length; i++) {
- //在可覆盖区域内更新最大的覆盖区域
- maxDistance = Math.max(maxDistance,i+nums[i]);
- //说明当前一步,再跳一步就到达了末尾
- if (maxDistance>=nums.length-1){
- count++;
- break;
- }
- //走到当前覆盖的最大区域时,更新下一步可达的最大区域
- if (i==curDistance){
- curDistance = maxDistance;
- count++;
- }
- }
- return count;
- }
-}
-```
-
-```java
-// 版本二
-class Solution {
- public int jump(int[] nums) {
- int result = 0;
- // 当前覆盖的最远距离下标
- int end = 0;
- // 下一步覆盖的最远距离下标
- int temp = 0;
- for (int i = 0; i <= end && end < nums.length - 1; ++i) {
- temp = Math.max(temp, i + nums[i]);
- // 可达位置的改变次数就是跳跃次数
- if (i == end) {
- end = temp;
- result++;
- }
- }
- return result;
- }
-}
-```
-
-### Python
-
-```python
-class Solution:
- def jump(self, nums: List[int]) -> int:
- if len(nums) == 1: return 0
- ans = 0
- curDistance = 0
- nextDistance = 0
- for i in range(len(nums)):
- nextDistance = max(i + nums[i], nextDistance)
- if i == curDistance:
- if curDistance != len(nums) - 1:
- ans += 1
- curDistance = nextDistance
- if nextDistance >= len(nums) - 1: break
- return ans
-```
-
-### Go
-```Go
-func jump(nums []int) int {
- dp := make([]int, len(nums))
- dp[0] = 0//初始第一格跳跃数一定为0
-
- for i := 1; i < len(nums); i++ {
- dp[i] = i
- for j := 0; j < i; j++ {
- if nums[j] + j >= i {//nums[j]为起点,j为往右跳的覆盖范围,这行表示从j能跳到i
- dp[i] = min(dp[j] + 1, dp[i])//更新最小能到i的跳跃次数
- }
- }
- }
- return dp[len(nums)-1]
-}
-
-func min(a, b int) int {
- if a < b {
- return a
- } else {
- return b
- }
-}
-```
-
-### Javascript
-```Javascript
-var jump = function(nums) {
- let curIndex = 0
- let nextIndex = 0
- let steps = 0
- for(let i = 0; i < nums.length - 1; i++) {
- nextIndex = Math.max(nums[i] + i, nextIndex)
- if(i === curIndex) {
- curIndex = nextIndex
- steps++
- }
- }
-
- return steps
-};
-```
-
-### TypeScript
-
-```typescript
-function jump(nums: number[]): number {
- const length: number = nums.length;
- let curFarthestIndex: number = 0,
- nextFarthestIndex: number = 0;
- let curIndex: number = 0;
- let stepNum: number = 0;
- while (curIndex < length - 1) {
- nextFarthestIndex = Math.max(nextFarthestIndex, curIndex + nums[curIndex]);
- if (curIndex === curFarthestIndex) {
- curFarthestIndex = nextFarthestIndex;
- stepNum++;
- }
- curIndex++;
- }
- return stepNum;
-};
-```
-
-
-
-
-
------------------------
-
diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md
index 4caff042..4e3ab24a 100644
--- a/problems/0045.跳跃游戏II.md
+++ b/problems/0045.跳跃游戏II.md
@@ -217,18 +217,26 @@ class Solution:
### Go
```Go
func jump(nums []int) int {
- dp:=make([]int ,len(nums))
- dp[0]=0
+ dp := make([]int, len(nums))
+ dp[0] = 0//初始第一格跳跃数一定为0
- for i:=1;ii{
- dp[i]=min(dp[j]+1,dp[i])
- }
- }
- }
- return dp[len(nums)-1]
+ for i := 1; i < len(nums); i++ {
+ dp[i] = i
+ for j := 0; j < i; j++ {
+ if nums[j] + j >= i {//nums[j]为起点,j为往右跳的覆盖范围,这行表示从j能跳到i
+ dp[i] = min(dp[j] + 1, dp[i])//更新最小能到i的跳跃次数
+ }
+ }
+ }
+ return dp[len(nums)-1]
+}
+
+func min(a, b int) int {
+ if a < b {
+ return a
+ } else {
+ return b
+ }
}
```
From d692ffe034aa1d7af9a4e5d76999ee6a506c23b9 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Tue, 3 May 2022 21:51:21 +0800
Subject: [PATCH 021/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880416.?=
=?UTF-8?q?=E5=88=86=E5=89=B2=E7=AD=89=E5=92=8C=E5=AD=90=E9=9B=86.md?=
=?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0416.分割等和子集.md | 55 +++++++++++++++++++++++++++++++++++
1 file changed, 55 insertions(+)
diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md
index b24fb365..20b7782d 100644
--- a/problems/0416.分割等和子集.md
+++ b/problems/0416.分割等和子集.md
@@ -416,6 +416,61 @@ var canPartition = function(nums) {
};
```
+TypeScript:
+
+> 一维数组,简洁
+
+```typescript
+function canPartition(nums: number[]): boolean {
+ const sum: number = nums.reduce((pre, cur) => pre + cur);
+ if (sum % 2 === 1) return false;
+ const bagSize: number = sum / 2;
+ const goodsNum: number = nums.length;
+ const dp: number[] = new Array(bagSize + 1).fill(0);
+ for (let i = 0; i < goodsNum; i++) {
+ for (let j = bagSize; j >= nums[i]; j--) {
+ dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]);
+ }
+ }
+ return dp[bagSize] === bagSize;
+};
+```
+
+> 二维数组,易懂
+
+```typescript
+function canPartition(nums: number[]): boolean {
+ /**
+ weightArr = nums;
+ valueArr = nums;
+ bagSize = sum / 2; (sum为nums各元素总和);
+ 按照0-1背包处理
+ */
+ const sum: number = nums.reduce((pre, cur) => pre + cur);
+ if (sum % 2 === 1) return false;
+ const bagSize: number = sum / 2;
+ const weightArr: number[] = nums;
+ const valueArr: number[] = nums;
+ const goodsNum: number = weightArr.length;
+ const dp: number[][] = new Array(goodsNum)
+ .fill(0)
+ .map(_ => new Array(bagSize + 1).fill(0));
+ for (let i = weightArr[0]; i <= bagSize; i++) {
+ dp[0][i] = valueArr[0];
+ }
+ for (let i = 1; i < goodsNum; i++) {
+ for (let j = 0; j <= bagSize; j++) {
+ if (j < weightArr[i]) {
+ dp[i][j] = dp[i - 1][j];
+ } else {
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weightArr[i]] + valueArr[i]);
+ }
+ }
+ }
+ return dp[goodsNum - 1][bagSize] === bagSize;
+};
+```
+
From 65cde78559bf18cced2e91b57fba8f92a66437a4 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Wed, 4 May 2022 12:57:05 +0800
Subject: [PATCH 022/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=881049.?=
=?UTF-8?q?=E6=9C=80=E5=90=8E=E4=B8=80=E5=9D=97=E7=9F=B3=E5=A4=B4=E7=9A=84?=
=?UTF-8?q?=E9=87=8D=E9=87=8FII.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0type?=
=?UTF-8?q?script=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/1049.最后一块石头的重量II.md | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md
index ee0ddef2..3d256c3d 100644
--- a/problems/1049.最后一块石头的重量II.md
+++ b/problems/1049.最后一块石头的重量II.md
@@ -277,5 +277,26 @@ var lastStoneWeightII = function (stones) {
};
```
+TypeScript:
+
+```typescript
+function lastStoneWeightII(stones: number[]): number {
+ const sum: number = stones.reduce((pre, cur) => pre + cur);
+ const bagSize: number = Math.floor(sum / 2);
+ const weightArr: number[] = stones;
+ const valueArr: number[] = stones;
+ const goodsNum: number = weightArr.length;
+ const dp: number[] = new Array(bagSize + 1).fill(0);
+ for (let i = 0; i < goodsNum; i++) {
+ for (let j = bagSize; j >= weightArr[i]; j--) {
+ dp[j] = Math.max(dp[j], dp[j - weightArr[i]] + valueArr[i]);
+ }
+ }
+ return sum - dp[bagSize] * 2;
+};
+```
+
+
+
-----------------------
From b9b7c1530abf7a4b6b68b0f732b5a69cbaae772c Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Wed, 4 May 2022 23:48:12 +0800
Subject: [PATCH 023/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880494.?=
=?UTF-8?q?=E7=9B=AE=E6=A0=87=E5=92=8C.md=EF=BC=89=EF=BC=9A=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0494.目标和.md | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md
index 99b76834..8ce1f6f1 100644
--- a/problems/0494.目标和.md
+++ b/problems/0494.目标和.md
@@ -351,6 +351,25 @@ const findTargetSumWays = (nums, target) => {
};
```
+TypeScript:
+
+```typescript
+function findTargetSumWays(nums: number[], target: number): number {
+ const sum: number = nums.reduce((pre, cur) => pre + cur);
+ if (Math.abs(target) > sum) return 0;
+ if ((target + sum) % 2 === 1) return 0;
+ const bagSize: number = (target + sum) / 2;
+ const dp: number[] = new Array(bagSize + 1).fill(0);
+ dp[0] = 1;
+ for (let i = 0; i < nums.length; i++) {
+ for (let j = bagSize; j >= nums[i]; j--) {
+ dp[j] += dp[j - nums[i]];
+ }
+ }
+ return dp[bagSize];
+};
+```
+
-----------------------
From 3c88974f92926f9280d71ea964bdb36b6f097044 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 5 May 2022 14:15:00 +0800
Subject: [PATCH 024/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880474.?=
=?UTF-8?q?=E4=B8=80=E5=92=8C=E9=9B=B6.md=EF=BC=89=EF=BC=9A=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0474.一和零.md | 123 ++++++++++++++++++++++++++++++++++++++++
1 file changed, 123 insertions(+)
diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md
index 964df4a8..d38ce03f 100644
--- a/problems/0474.一和零.md
+++ b/problems/0474.一和零.md
@@ -323,6 +323,129 @@ const findMaxForm = (strs, m, n) => {
};
```
+TypeScript:
+
+> 滚动数组,二维数组法
+
+```typescript
+type BinaryInfo = { numOfZero: number, numOfOne: number };
+function findMaxForm(strs: string[], m: number, n: number): number {
+ const goodsNum: number = strs.length;
+ const dp: number[][] = new Array(m + 1).fill(0)
+ .map(_ => new Array(n + 1).fill(0));
+ for (let i = 0; i < goodsNum; i++) {
+ const { numOfZero, numOfOne } = countBinary(strs[i]);
+ for (let j = m; j >= numOfZero; j--) {
+ for (let k = n; k >= numOfOne; k--) {
+ dp[j][k] = Math.max(dp[j][k], dp[j - numOfZero][k - numOfOne] + 1);
+ }
+ }
+ }
+ return dp[m][n];
+};
+function countBinary(str: string): BinaryInfo {
+ let numOfZero: number = 0,
+ numOfOne: number = 0;
+ for (let s of str) {
+ if (s === '0') {
+ numOfZero++;
+ } else {
+ numOfOne++;
+ }
+ }
+ return { numOfZero, numOfOne };
+}
+```
+
+> 传统背包,三维数组法
+
+```typescript
+type BinaryInfo = { numOfZero: number, numOfOne: number };
+function findMaxForm(strs: string[], m: number, n: number): number {
+ /**
+ dp[i][j][k]: 前i个物品中, 背包的0容量为j, 1容量为k, 最多能放的物品数量
+ */
+ const goodsNum: number = strs.length;
+ const dp: number[][][] = new Array(goodsNum).fill(0)
+ .map(_ => new Array(m + 1)
+ .fill(0)
+ .map(_ => new Array(n + 1).fill(0))
+ );
+ const { numOfZero, numOfOne } = countBinary(strs[0]);
+ for (let i = numOfZero; i <= m; i++) {
+ for (let j = numOfOne; j <= n; j++) {
+ dp[0][i][j] = 1;
+ }
+ }
+ for (let i = 1; i < goodsNum; i++) {
+ const { numOfZero, numOfOne } = countBinary(strs[i]);
+ for (let j = 0; j <= m; j++) {
+ for (let k = 0; k <= n; k++) {
+ if (j < numOfZero || k < numOfOne) {
+ dp[i][j][k] = dp[i - 1][j][k];
+ } else {
+ dp[i][j][k] = Math.max(dp[i - 1][j][k], dp[i - 1][j - numOfZero][k - numOfOne] + 1);
+ }
+ }
+ }
+ }
+ return dp[dp.length - 1][m][n];
+};
+function countBinary(str: string): BinaryInfo {
+ let numOfZero: number = 0,
+ numOfOne: number = 0;
+ for (let s of str) {
+ if (s === '0') {
+ numOfZero++;
+ } else {
+ numOfOne++;
+ }
+ }
+ return { numOfZero, numOfOne };
+}
+```
+
+> 回溯法(会超时)
+
+```typescript
+function findMaxForm(strs: string[], m: number, n: number): number {
+ /**
+ 思路:暴力枚举strs的所有子集,记录符合条件子集的最大长度
+ */
+ let resMax: number = 0;
+ backTrack(strs, m, n, 0, []);
+ return resMax;
+ function backTrack(
+ strs: string[], m: number, n: number,
+ startIndex: number, route: string[]
+ ): void {
+ if (startIndex === strs.length) return;
+ for (let i = startIndex, length = strs.length; i < length; i++) {
+ route.push(strs[i]);
+ if (isValidSubSet(route, m, n)) {
+ resMax = Math.max(resMax, route.length);
+ backTrack(strs, m, n, i + 1, route);
+ }
+ route.pop();
+ }
+ }
+};
+function isValidSubSet(strs: string[], m: number, n: number): boolean {
+ let zeroNum: number = 0,
+ oneNum: number = 0;
+ strs.forEach(str => {
+ for (let s of str) {
+ if (s === '0') {
+ zeroNum++;
+ } else {
+ oneNum++;
+ }
+ }
+ });
+ return zeroNum <= m && oneNum <= n;
+}
+```
+
-----------------------
From 1e9cecb665acd511660a9c8c8af48868e20bb871 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 5 May 2022 16:53:38 +0800
Subject: [PATCH 025/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E8=83=8C?=
=?UTF-8?q?=E5=8C=85=E9=97=AE=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80?=
=?UTF-8?q?=E5=AE=8C=E5=85=A8=E8=83=8C=E5=8C=85.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/背包问题理论基础完全背包.md | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md
index faa1dc46..936a80c7 100644
--- a/problems/背包问题理论基础完全背包.md
+++ b/problems/背包问题理论基础完全背包.md
@@ -340,6 +340,27 @@ function test_completePack2() {
}
```
+TypeScript:
+
+```typescript
+// 先遍历物品,再遍历背包容量
+function test_CompletePack(): void {
+ const weight: number[] = [1, 3, 4];
+ const value: number[] = [15, 20, 30];
+ const bagSize: number = 4;
+ const dp: number[] = new Array(bagSize + 1).fill(0);
+ for (let i = 0; i < weight.length; i++) {
+ for (let j = weight[i]; j <= bagSize; j++) {
+ dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]);
+ }
+ }
+ console.log(dp);
+}
+test_CompletePack();
+```
+
+
+
-----------------------
From b82984e24b23940aa95da2a0283ae4cf3c706f7a Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 5 May 2022 18:11:41 +0800
Subject: [PATCH 026/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880518.?=
=?UTF-8?q?=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2II.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0518.零钱兑换II.md | 15 +++++++++++++++
1 file changed, 15 insertions(+)
diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md
index e72c5f85..8faf6698 100644
--- a/problems/0518.零钱兑换II.md
+++ b/problems/0518.零钱兑换II.md
@@ -258,6 +258,21 @@ const change = (amount, coins) => {
}
```
+TypeScript:
+
+```typescript
+function change(amount: number, coins: number[]): number {
+ const dp: number[] = new Array(amount + 1).fill(0);
+ dp[0] = 1;
+ for (let i = 0, length = coins.length; i < length; i++) {
+ for (let j = coins[i]; j <= amount; j++) {
+ dp[j] += dp[j - coins[i]];
+ }
+ }
+ return dp[amount];
+};
+```
+
-----------------------
From cb7bf67a4e3a277ecf53ce37d0556c8e2e65f9f3 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Fri, 6 May 2022 11:08:47 +0800
Subject: [PATCH 027/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880377.?=
=?UTF-8?q?=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8C=E2=85=A3.md=EF=BC=89?=
=?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0377.组合总和Ⅳ.md | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/problems/0377.组合总和Ⅳ.md b/problems/0377.组合总和Ⅳ.md
index aaf27e61..1d808a3a 100644
--- a/problems/0377.组合总和Ⅳ.md
+++ b/problems/0377.组合总和Ⅳ.md
@@ -221,7 +221,27 @@ const combinationSum4 = (nums, target) => {
};
```
+TypeScript:
+
+```typescript
+function combinationSum4(nums: number[], target: number): number {
+ const dp: number[] = new Array(target + 1).fill(0);
+ dp[0] = 1;
+ // 遍历背包
+ for (let i = 1; i <= target; i++) {
+ // 遍历物品
+ for (let j = 0, length = nums.length; j < length; j++) {
+ if (i >= nums[j]) {
+ dp[i] += dp[i - nums[j]];
+ }
+ }
+ }
+ return dp[target];
+};
+```
+
Rust
+
```Rust
impl Solution {
pub fn combination_sum4(nums: Vec, target: i32) -> i32 {
From 100a4e2b46abf913dacc62637da7faf27bfe060e Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Fri, 6 May 2022 11:56:19 +0800
Subject: [PATCH 028/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880070.?=
=?UTF-8?q?=E7=88=AC=E6=A5=BC=E6=A2=AF=E5=AE=8C=E5=85=A8=E8=83=8C=E5=8C=85?=
=?UTF-8?q?=E7=89=88=E6=9C=AC.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?=
=?UTF-8?q?ript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0070.爬楼梯完全背包版本.md | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/problems/0070.爬楼梯完全背包版本.md b/problems/0070.爬楼梯完全背包版本.md
index 2286de2d..0f482bb7 100644
--- a/problems/0070.爬楼梯完全背包版本.md
+++ b/problems/0070.爬楼梯完全背包版本.md
@@ -199,6 +199,28 @@ var climbStairs = function(n) {
};
```
+TypeScript:
+
+```typescript
+function climbStairs(n: number): number {
+ const m: number = 2; // 本题m为2
+ const dp: number[] = new Array(n + 1).fill(0);
+ dp[0] = 1;
+ // 遍历背包
+ for (let i = 1; i <= n; i++) {
+ // 遍历物品
+ for (let j = 1; j <= m; j++) {
+ if (j <= i) {
+ dp[i] += dp[i - j];
+ }
+ }
+ }
+ return dp[n];
+};
+```
+
+
+
-----------------------
From cb6f015186ae9d6af13cddf9b929f7bbdfe9bc29 Mon Sep 17 00:00:00 2001
From: cy948 <67412196+cy948@users.noreply.github.com>
Date: Fri, 6 May 2022 14:43:58 +0800
Subject: [PATCH 029/162] =?UTF-8?q?Update=200112.=E8=B7=AF=E5=BE=84?=
=?UTF-8?q?=E6=80=BB=E5=92=8C.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
修复了 0113.路径总和-ii 中Java递归解法中的类名大小写问题。
---
problems/0112.路径总和.md | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md
index 41463ec1..2fdd7741 100644
--- a/problems/0112.路径总和.md
+++ b/problems/0112.路径总和.md
@@ -377,22 +377,22 @@ class solution {
```java
class solution {
- public list> pathsum(treenode root, int targetsum) {
- list> res = new arraylist<>();
+ public List> pathsum(TreeNode root, int targetsum) {
+ List> res = new ArrayList<>();
if (root == null) return res; // 非空判断
-
- list path = new linkedlist<>();
+
+ List path = new LinkedList<>();
preorderdfs(root, targetsum, res, path);
return res;
}
- public void preorderdfs(treenode root, int targetsum, list> res, list path) {
+ public void preorderdfs(TreeNode root, int targetsum, List> res, List path) {
path.add(root.val);
// 遇到了叶子节点
if (root.left == null && root.right == null) {
// 找到了和为 targetsum 的路径
if (targetsum - root.val == 0) {
- res.add(new arraylist<>(path));
+ res.add(new ArrayList<>(path));
}
return; // 如果和不为 targetsum,返回
}
From 82a58bc20249bb248dbbb0d90771db0ea60bf017 Mon Sep 17 00:00:00 2001
From: Jamcy123 <1219502823@qq.com>
Date: Fri, 6 May 2022 15:49:43 +0800
Subject: [PATCH 030/162] =?UTF-8?q?1005.K=E6=AC=A1=E5=8F=96=E5=8F=8D?=
=?UTF-8?q?=E5=90=8E=E6=9C=80=E5=A4=A7=E5=8C=96=E7=9A=84=E6=95=B0=E7=BB=84?=
=?UTF-8?q?=E5=92=8C?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/1005.K次取反后最大化的数组和.md | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md
index 79767deb..202534da 100644
--- a/problems/1005.K次取反后最大化的数组和.md
+++ b/problems/1005.K次取反后最大化的数组和.md
@@ -209,6 +209,22 @@ var largestSumAfterKNegations = function(nums, k) {
return a + b
})
};
+
+// 版本二 (优化: 一次遍历)
+var largestSumAfterKNegations = function(nums, k) {
+ nums.sort((a, b) => Math.abs(b) - Math.abs(a)); // 排序
+ let sum = 0;
+ for(let i = 0; i < nums.length; i++) {
+ if(nums[i] < 0 && k-- > 0) { // 负数取反(k 数量足够时)
+ nums[i] = -nums[i];
+ }
+ sum += nums[i]; // 求和
+ }
+ if(k % 2 > 0) { // k 有多余的(k若消耗完则应为 -1)
+ sum -= 2 * nums[nums.length - 1]; // 减去两倍的最小值(因为之前加过一次)
+ }
+ return sum;
+};
```
From 08ae851e75f735f45f033a0c5455aef198d3cc92 Mon Sep 17 00:00:00 2001
From: wang <472146630@qq.com>
Date: Fri, 6 May 2022 20:45:29 +0800
Subject: [PATCH 031/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A01035.=E4=B8=8D?=
=?UTF-8?q?=E7=9B=B8=E4=BA=A4=E7=9A=84=E7=BA=BF=E5=92=8C1143.=E6=9C=80?=
=?UTF-8?q?=E9=95=BF=E5=85=AC=E5=85=B1=E5=AD=90=E5=BA=8F=E5=88=97?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/1035.不相交的线.md | 20 ++++++++-
problems/1143.最长公共子序列.md | 80 +++++++++++++++++++++------------
2 files changed, 70 insertions(+), 30 deletions(-)
diff --git a/problems/1035.不相交的线.md b/problems/1035.不相交的线.md
index 0602e111..279ed816 100644
--- a/problems/1035.不相交的线.md
+++ b/problems/1035.不相交的线.md
@@ -111,7 +111,6 @@ class Solution:
Golang:
```go
-
func maxUncrossedLines(A []int, B []int) int {
m, n := len(A), len(B)
dp := make([][]int, m+1)
@@ -140,7 +139,26 @@ func max(a, b int) int {
}
```
+Rust:
+```rust
+pub fn max_uncrossed_lines(nums1: Vec, nums2: Vec) -> i32 {
+ let (n, m) = (nums1.len(), nums2.len());
+ let mut last = vec![0; m + 1]; // 记录滚动数组
+ let mut dp = vec![0; m + 1];
+ for i in 1..=n {
+ dp.swap_with_slice(&mut last);
+ for j in 1..=m {
+ if nums1[i - 1] == nums2[j - 1] {
+ dp[j] = last[j - 1] + 1;
+ } else {
+ dp[j] = last[j].max(dp[j - 1]);
+ }
+ }
+ }
+ dp[m]
+}
+```
JavaScript:
diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md
index fdcc7619..ecedf89b 100644
--- a/problems/1143.最长公共子序列.md
+++ b/problems/1143.最长公共子序列.md
@@ -4,40 +4,40 @@
参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!
-## 1143.最长公共子序列
+## 1143.最长公共子序列
[力扣题目链接](https://leetcode-cn.com/problems/longest-common-subsequence/)
-给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。
+给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。
-一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
+一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
-例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。
+例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。
-若这两个字符串没有公共子序列,则返回 0。
+若这两个字符串没有公共子序列,则返回 0。
-示例 1:
+示例 1:
-输入:text1 = "abcde", text2 = "ace"
-输出:3
-解释:最长公共子序列是 "ace",它的长度为 3。
+输入:text1 = "abcde", text2 = "ace"
+输出:3
+解释:最长公共子序列是 "ace",它的长度为 3。
-示例 2:
-输入:text1 = "abc", text2 = "abc"
-输出:3
-解释:最长公共子序列是 "abc",它的长度为 3。
+示例 2:
+输入:text1 = "abc", text2 = "abc"
+输出:3
+解释:最长公共子序列是 "abc",它的长度为 3。
-示例 3:
-输入:text1 = "abc", text2 = "def"
-输出:0
-解释:两个字符串没有公共子序列,返回 0。
+示例 3:
+输入:text1 = "abc", text2 = "def"
+输出:0
+解释:两个字符串没有公共子序列,返回 0。
-提示:
+提示:
* 1 <= text1.length <= 1000
* 1 <= text2.length <= 1000
输入的字符串只含有小写英文字符。
-## 思路
+## 思路
本题和[动态规划:718. 最长重复子数组](https://programmercarl.com/0718.最长重复子数组.html)区别在于这里不要求是连续的了,但要有相对顺序,即:"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。
@@ -45,21 +45,21 @@
1. 确定dp数组(dp table)以及下标的含义
-dp[i][j]:长度为[0, i - 1]的字符串text1与长度为[0, j - 1]的字符串text2的最长公共子序列为dp[i][j]
+dp[i][j]:长度为[0, i - 1]的字符串text1与长度为[0, j - 1]的字符串text2的最长公共子序列为dp[i][j]
-有同学会问:为什么要定义长度为[0, i - 1]的字符串text1,定义为长度为[0, i]的字符串text1不香么?
+有同学会问:为什么要定义长度为[0, i - 1]的字符串text1,定义为长度为[0, i]的字符串text1不香么?
这样定义是为了后面代码实现方便,如果非要定义为为长度为[0, i]的字符串text1也可以,大家可以试一试!
2. 确定递推公式
-主要就是两大情况: text1[i - 1] 与 text2[j - 1]相同,text1[i - 1] 与 text2[j - 1]不相同
+主要就是两大情况: text1[i - 1] 与 text2[j - 1]相同,text1[i - 1] 与 text2[j - 1]不相同
-如果text1[i - 1] 与 text2[j - 1]相同,那么找到了一个公共元素,所以dp[i][j] = dp[i - 1][j - 1] + 1;
+如果text1[i - 1] 与 text2[j - 1]相同,那么找到了一个公共元素,所以dp[i][j] = dp[i - 1][j - 1] + 1;
如果text1[i - 1] 与 text2[j - 1]不相同,那就看看text1[0, i - 2]与text2[0, j - 1]的最长公共子序列 和 text1[0, i - 1]与text2[0, j - 2]的最长公共子序列,取最大的。
-即:dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
+即:dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
代码如下:
@@ -71,9 +71,9 @@ if (text1[i - 1] == text2[j - 1]) {
}
```
-3. dp数组如何初始化
+3. dp数组如何初始化
-先看看dp[i][0]应该是多少呢?
+先看看dp[i][0]应该是多少呢?
test1[0, i-1]和空串的最长公共子序列自然是0,所以dp[i][0] = 0;
@@ -101,7 +101,7 @@ vector> dp(text1.size() + 1, vector(text2.size() + 1, 0));

-最后红框dp[text1.size()][text2.size()]为最终结果
+最后红框dp[text1.size()][text2.size()]为最终结果
以上分析完毕,C++代码如下:
@@ -158,7 +158,7 @@ class Solution:
for i in range(1, len2):
for j in range(1, len1): # 开始列出状态转移方程
if text1[j-1] == text2[i-1]:
- dp[i][j] = dp[i-1][j-1]+1
+ dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]
@@ -189,10 +189,32 @@ func longestCommonSubsequence(text1 string, text2 string) int {
func max(a,b int)int {
if a>b{
- return a
+ return a
}
return b
}
+
+```
+
+Rust:
+```rust
+pub fn longest_common_subsequence(text1: String, text2: String) -> i32 {
+ let (n, m) = (text1.len(), text2.len());
+ let (s1, s2) = (text1.as_bytes(), text2.as_bytes());
+ let mut dp = vec![0; m + 1];
+ let mut last = vec![0; m + 1];
+ for i in 1..=n {
+ dp.swap_with_slice(&mut last);
+ for j in 1..=m {
+ dp[j] = if s1[i - 1] == s2[j - 1] {
+ last[j - 1] + 1
+ } else {
+ last[j].max(dp[j - 1])
+ };
+ }
+ }
+ dp[m]
+}
```
Javascript:
From da464016574f14c43fe1e9f7c0d808ed7ea304fb Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sun, 8 May 2022 10:29:33 +0800
Subject: [PATCH 032/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880322.?=
=?UTF-8?q?=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0322.零钱兑换.md | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/problems/0322.零钱兑换.md b/problems/0322.零钱兑换.md
index 3a8d0662..1df8d613 100644
--- a/problems/0322.零钱兑换.md
+++ b/problems/0322.零钱兑换.md
@@ -322,7 +322,21 @@ const coinChange = (coins, amount) => {
}
```
+TypeScript:
+```typescript
+function coinChange(coins: number[], amount: number): number {
+ const dp: number[] = new Array(amount + 1).fill(Infinity);
+ dp[0] = 0;
+ for (let i = 0; i < coins.length; i++) {
+ for (let j = coins[i]; j <= amount; j++) {
+ if (dp[j - coins[i]] === Infinity) continue;
+ dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1);
+ }
+ }
+ return dp[amount] === Infinity ? -1 : dp[amount];
+};
+```
-----------------------
From 2722fe7b5eceec7d746f94a63683430205839469 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sun, 8 May 2022 11:07:39 +0800
Subject: [PATCH 033/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880279.?=
=?UTF-8?q?=E5=AE=8C=E5=85=A8=E5=B9=B3=E6=96=B9=E6=95=B0.md=EF=BC=89?=
=?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0279.完全平方数.md | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md
index 9bad2085..5b15639c 100644
--- a/problems/0279.完全平方数.md
+++ b/problems/0279.完全平方数.md
@@ -355,5 +355,24 @@ var numSquares2 = function(n) {
};
```
+TypeScript:
+
+```typescript
+function numSquares(n: number): number {
+ const goodsNum: number = Math.floor(Math.sqrt(n));
+ const dp: number[] = new Array(n + 1).fill(Infinity);
+ dp[0] = 0;
+ for (let i = 1; i <= goodsNum; i++) {
+ const tempVal: number = i * i;
+ for (let j = tempVal; j <= n; j++) {
+ dp[j] = Math.min(dp[j], dp[j - tempVal] + 1);
+ }
+ }
+ return dp[n];
+};
+```
+
+
+
-----------------------
From 9b6a447674f3290541e46088962e1e3aa764d827 Mon Sep 17 00:00:00 2001
From: Hayden-Chang <62008508+Hayden-Chang@users.noreply.github.com>
Date: Sun, 8 May 2022 14:20:09 +0800
Subject: [PATCH 034/162] explain the reason for reverse traversal
---
problems/背包理论基础01背包-2.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md
index dabdfb2d..ea7c53ad 100644
--- a/problems/背包理论基础01背包-2.md
+++ b/problems/背包理论基础01背包-2.md
@@ -136,6 +136,7 @@ dp[1] = dp[1 - weight[0]] + value[0] = 15
不可以!
因为一维dp的写法,背包容量一定是要倒序遍历(原因上面已经讲了),如果遍历背包容量放在上一层,那么每个dp[j]就只会放入一个物品,即:背包里只放入了一个物品。
+倒叙遍历的原因是,本质上还是一个对二维数组的遍历,并且右下角的值依赖上一层左上角的值,因此需要保证左边的值仍然是上一层的,从右向左覆盖。
(这里如果读不懂,就在回想一下dp[j]的定义,或者就把两个for循环顺序颠倒一下试试!)
From 80167289e4895c4116b61a5c2a4fa22e9e2e88b5 Mon Sep 17 00:00:00 2001
From: Hayden-Chang <62008508+Hayden-Chang@users.noreply.github.com>
Date: Sun, 8 May 2022 14:24:09 +0800
Subject: [PATCH 035/162] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E7=90=86?=
=?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-2.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/背包理论基础01背包-2.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md
index ea7c53ad..eae01158 100644
--- a/problems/背包理论基础01背包-2.md
+++ b/problems/背包理论基础01背包-2.md
@@ -136,7 +136,8 @@ dp[1] = dp[1 - weight[0]] + value[0] = 15
不可以!
因为一维dp的写法,背包容量一定是要倒序遍历(原因上面已经讲了),如果遍历背包容量放在上一层,那么每个dp[j]就只会放入一个物品,即:背包里只放入了一个物品。
-倒叙遍历的原因是,本质上还是一个对二维数组的遍历,并且右下角的值依赖上一层左上角的值,因此需要保证左边的值仍然是上一层的,从右向左覆盖。
+
+倒序遍历的原因是,本质上还是一个对二维数组的遍历,并且右下角的值依赖上一层左上角的值,因此需要保证左边的值仍然是上一层的,从右向左覆盖。
(这里如果读不懂,就在回想一下dp[j]的定义,或者就把两个for循环顺序颠倒一下试试!)
From 2fb34b30b38ee73624d65d183955cef3a80caced Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sun, 8 May 2022 18:28:32 +0800
Subject: [PATCH 036/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880139.?=
=?UTF-8?q?=E5=8D=95=E8=AF=8D=E6=8B=86=E5=88=86.md=EF=BC=89:=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0139.单词拆分.md | 42 +++++++++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md
index ac834f04..5b4e92b9 100644
--- a/problems/0139.单词拆分.md
+++ b/problems/0139.单词拆分.md
@@ -345,6 +345,48 @@ const wordBreak = (s, wordDict) => {
}
```
+TypeScript:
+
+> 动态规划
+
+```typescript
+function wordBreak(s: string, wordDict: string[]): boolean {
+ const dp: boolean[] = new Array(s.length + 1).fill(false);
+ dp[0] = true;
+ for (let i = 1; i <= s.length; i++) {
+ for (let j = 0; j < i; j++) {
+ const tempStr: string = s.slice(j, i);
+ if (wordDict.includes(tempStr) && dp[j] === true) {
+ dp[i] = true;
+ break;
+ }
+ }
+ }
+ return dp[s.length];
+};
+```
+
+> 记忆化回溯
+
+```typescript
+function wordBreak(s: string, wordDict: string[]): boolean {
+ // 只需要记忆结果为false的情况
+ const memory: boolean[] = [];
+ return backTracking(s, wordDict, 0, memory);
+ function backTracking(s: string, wordDict: string[], startIndex: number, memory: boolean[]): boolean {
+ if (startIndex >= s.length) return true;
+ if (memory[startIndex] === false) return false;
+ for (let i = startIndex + 1, length = s.length; i <= length; i++) {
+ const str: string = s.slice(startIndex, i);
+ if (wordDict.includes(str) && backTracking(s, wordDict, i, memory))
+ return true;
+ }
+ memory[startIndex] = false;
+ return false;
+ }
+};
+```
+
-----------------------
From 21475ad21864ce33fb5a6a113581f2c346be78b6 Mon Sep 17 00:00:00 2001
From: languagege
Date: Mon, 9 May 2022 18:51:39 +0800
Subject: [PATCH 037/162] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E4=BA=86=E5=85=B6?=
=?UTF-8?q?=E4=B8=AD=E4=B8=80=E4=B8=AA=E9=94=99=E5=88=AB=E5=AD=97?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0027.移除元素.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md
index 590cf0b9..3a93ac88 100644
--- a/problems/0027.移除元素.md
+++ b/problems/0027.移除元素.md
@@ -81,7 +81,7 @@ public:
**双指针法(快慢指针法)在数组和链表的操作中是非常常见的,很多考察数组、链表、字符串等操作的面试题,都使用双指针法。**
-后序都会一一介绍到,本题代码如下:
+后续都会一一介绍到,本题代码如下:
```CPP
// 时间复杂度:O(n)
From 75198263f91484020c4a4dde421d9ecd989422dd Mon Sep 17 00:00:00 2001
From: changjunkui <506678275@qq.com>
Date: Tue, 10 May 2022 08:16:53 +0800
Subject: [PATCH 038/162] =?UTF-8?q?Update=200019.=E5=88=A0=E9=99=A4?=
=?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=ACN?=
=?UTF-8?q?=E4=B8=AA=E8=8A=82=E7=82=B9.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
方面改为方便
---
problems/0019.删除链表的倒数第N个节点.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md
index 813e9b02..b3030a81 100644
--- a/problems/0019.删除链表的倒数第N个节点.md
+++ b/problems/0019.删除链表的倒数第N个节点.md
@@ -39,7 +39,7 @@
分为如下几步:
-* 首先这里我推荐大家使用虚拟头结点,这样方面处理删除实际头结点的逻辑,如果虚拟头结点不清楚,可以看这篇: [链表:听说用虚拟头节点会方便很多?](https://programmercarl.com/0203.移除链表元素.html)
+* 首先这里我推荐大家使用虚拟头结点,这样方便处理删除实际头结点的逻辑,如果虚拟头结点不清楚,可以看这篇: [链表:听说用虚拟头节点会方便很多?](https://programmercarl.com/0203.移除链表元素.html)
* 定义fast指针和slow指针,初始值为虚拟头结点,如图:
From 8bab33d0bba8a080fb614bec6be3b0a5961d7727 Mon Sep 17 00:00:00 2001
From: wang <472146630@qq.com>
Date: Tue, 10 May 2022 21:27:54 +0800
Subject: [PATCH 039/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200300.=E6=9C=80?=
=?UTF-8?q?=E9=95=BF=E4=B8=8A=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97=E3=80=81?=
=?UTF-8?q?0322.=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2=E3=80=810518.?=
=?UTF-8?q?=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2II=20=E5=92=8C0674.?=
=?UTF-8?q?=E6=9C=80=E9=95=BF=E8=BF=9E=E7=BB=AD=E9=80=92=E5=A2=9E=E5=BA=8F?=
=?UTF-8?q?=E5=88=97=E7=9A=84rust=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0300.最长上升子序列.md | 17 +++++++++++++++++
problems/0322.零钱兑换.md | 20 +++++++++++++++++++-
problems/0518.零钱兑换II.md | 16 ++++++++++++++++
problems/0674.最长连续递增序列.md | 19 +++++++++++++++++++
4 files changed, 71 insertions(+), 1 deletion(-)
diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md
index dfdd5125..f53d19a1 100644
--- a/problems/0300.最长上升子序列.md
+++ b/problems/0300.最长上升子序列.md
@@ -168,6 +168,23 @@ func lengthOfLIS(nums []int ) int {
}
```
+Rust:
+```rust
+pub fn length_of_lis(nums: Vec) -> i32 {
+ let mut dp = vec![1; nums.len() + 1];
+ let mut result = 1;
+ for i in 1..nums.len() {
+ for j in 0..i {
+ if nums[j] < nums[i] {
+ dp[i] = dp[i].max(dp[j] + 1);
+ }
+ result = result.max(dp[i]);
+ }
+ }
+ result
+}
+```
+
Javascript
```javascript
const lengthOfLIS = (nums) => {
diff --git a/problems/0322.零钱兑换.md b/problems/0322.零钱兑换.md
index 3a8d0662..43c735be 100644
--- a/problems/0322.零钱兑换.md
+++ b/problems/0322.零钱兑换.md
@@ -220,7 +220,7 @@ class Solution:
for j in range(coin, amount + 1):
dp[j] = min(dp[j], dp[j - coin] + 1)
return dp[amount] if dp[amount] < amount + 1 else -1
-
+
def coinChange1(self, coins: List[int], amount: int) -> int:
'''版本二'''
# 初始化
@@ -302,6 +302,24 @@ func min(a, b int) int {
```
+Rust:
+
+```rust
+pub fn coin_change(coins: Vec, amount: i32) -> i32 {
+ let amount = amount as usize;
+ let mut dp = vec![i32::MAX; amount + 1];
+ dp[0] = 0;
+ for i in 0..coins.len() {
+ for j in coins[i] as usize..=amount {
+ if dp[j - coins[i] as usize] != i32::MAX {
+ dp[j] = dp[j].min(dp[j - coins[i] as usize] + 1);
+ }
+ }
+ }
+ if dp[amount] == i32::MAX { -1 } else { dp[amount] }
+}
+```
+
Javascript:
```javascript
const coinChange = (coins, amount) => {
diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md
index e72c5f85..0e4a3987 100644
--- a/problems/0518.零钱兑换II.md
+++ b/problems/0518.零钱兑换II.md
@@ -242,6 +242,22 @@ func change(amount int, coins []int) int {
}
```
+Rust:
+```rust
+pub fn change(amount: i32, coins: Vec) -> i32 {
+ let amount = amount as usize;
+ let coins = coins.iter().map(|&c|c as usize).collect::>();
+ let mut dp = vec![0usize; amount + 1];
+ dp[0] = 1;
+ for i in 0..coins.len() {
+ for j in coins[i]..=amount {
+ dp[j] += dp[j - coins[i]];
+ }
+ }
+ dp[amount] as i32
+}
+```
+
Javascript:
```javascript
const change = (amount, coins) => {
diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md
index e941d242..36471490 100644
--- a/problems/0674.最长连续递增序列.md
+++ b/problems/0674.最长连续递增序列.md
@@ -218,6 +218,7 @@ class Solution:
return result
```
+
> 贪心法:
```python
class Solution:
@@ -237,6 +238,24 @@ class Solution:
Go:
+Rust:
+```rust
+pub fn find_length_of_lcis(nums: Vec) -> i32 {
+ if nums.is_empty() {
+ return 0;
+ }
+ let mut result = 1;
+ let mut dp = vec![1; nums.len()];
+ for i in 1..nums.len() {
+ if nums[i - 1] < nums[i] {
+ dp[i] = dp[i - 1] + 1;
+ result = result.max(dp[i]);
+ }
+ }
+ result
+}
+```
+
Javascript:
> 动态规划:
From c62d518e149295783d219ec1871da84af8e5546e Mon Sep 17 00:00:00 2001
From: FizzerYu <36132150+FizzerYu@users.noreply.github.com>
Date: Wed, 11 May 2022 01:17:08 +0800
Subject: [PATCH 040/162] fix bug
---
problems/0701.二叉搜索树中的插入操作.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md
index df6a3954..50e39ade 100644
--- a/problems/0701.二叉搜索树中的插入操作.md
+++ b/problems/0701.二叉搜索树中的插入操作.md
@@ -279,7 +279,7 @@ class Solution:
root.right = self.insertIntoBST(root.right, val)
# 返回更新后的以当前root为根节点的新树
- return roo
+ return root
```
**递归法** - 无返回值
From cc2c2adb0987a5e2e82eed75a93be068da6388a4 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 11 May 2022 16:03:22 +0800
Subject: [PATCH 041/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200977.=E6=9C=89?=
=?UTF-8?q?=E5=BA=8F=E6=95=B0=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9.md=20Sca?=
=?UTF-8?q?la=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0977.有序数组的平方.md | 34 +++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md
index 24276bcf..0e79a3d6 100644
--- a/problems/0977.有序数组的平方.md
+++ b/problems/0977.有序数组的平方.md
@@ -358,7 +358,41 @@ class Solution {
}
}
```
+Scala:
+双指针:
+```scala
+object Solution {
+ def sortedSquares(nums: Array[Int]): Array[Int] = {
+ val res: Array[Int] = new Array[Int](nums.length)
+ var top = nums.length - 1
+ var i = 0
+ var j = nums.length - 1
+ while (i <= j) {
+ if (nums(i) * nums(i) <= nums(j) * nums(j)) {
+ // 当左侧平方小于等于右侧,res数组顶部放右侧的平方,并且top下移,j左移
+ res(top) = nums(j) * nums(j)
+ top -= 1
+ j -= 1
+ } else {
+ // 当左侧平方大于右侧,res数组顶部放左侧的平方,并且top下移,i右移
+ res(top) = nums(i) * nums(i)
+ top -= 1
+ i += 1
+ }
+ }
+ res
+ }
+}
+```
+骚操作(暴力思路):
+```scala
+object Solution {
+ def sortedSquares(nums: Array[Int]): Array[Int] = {
+ nums.map(x=>{x*x}).sortWith(_ < _)
+ }
+}
+```
-----------------------
From 842c04208b163c4782fb7070d949f5feb0c01bee Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Wed, 11 May 2022 16:35:58 +0800
Subject: [PATCH 042/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E8=83=8C?=
=?UTF-8?q?=E5=8C=85=E9=97=AE=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80?=
=?UTF-8?q?=E5=A4=9A=E9=87=8D=E8=83=8C=E5=8C=85.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/背包问题理论基础多重背包.md | 58 ++++++++++++++++++++++++++++
1 file changed, 58 insertions(+)
diff --git a/problems/背包问题理论基础多重背包.md b/problems/背包问题理论基础多重背包.md
index a988db2c..712380f4 100644
--- a/problems/背包问题理论基础多重背包.md
+++ b/problems/背包问题理论基础多重背包.md
@@ -334,6 +334,64 @@ func Test_multiplePack(t *testing.T) {
PASS
```
+TypeScript:
+
+> 版本一(改变数据源):
+
+```typescript
+function testMultiPack() {
+ const bagSize: number = 10;
+ const weightArr: number[] = [1, 3, 4],
+ valueArr: number[] = [15, 20, 30],
+ amountArr: number[] = [2, 3, 2];
+ for (let i = 0, length = amountArr.length; i < length; i++) {
+ while (amountArr[i] > 1) {
+ weightArr.push(weightArr[i]);
+ valueArr.push(valueArr[i]);
+ amountArr[i]--;
+ }
+ }
+ const goodsNum: number = weightArr.length;
+ const dp: number[] = new Array(bagSize + 1).fill(0);
+ // 遍历物品
+ for (let i = 0; i < goodsNum; i++) {
+ // 遍历背包容量
+ for (let j = bagSize; j >= weightArr[i]; j--) {
+ dp[j] = Math.max(dp[j], dp[j - weightArr[i]] + valueArr[i]);
+ }
+ }
+ console.log(dp);
+}
+testMultiPack();
+```
+
+> 版本二(改变遍历方式):
+
+```typescript
+function testMultiPack() {
+ const bagSize: number = 10;
+ const weightArr: number[] = [1, 3, 4],
+ valueArr: number[] = [15, 20, 30],
+ amountArr: number[] = [2, 3, 2];
+ const goodsNum: number = weightArr.length;
+ const dp: number[] = new Array(bagSize + 1).fill(0);
+ // 遍历物品
+ for (let i = 0; i < goodsNum; i++) {
+ // 遍历物品个数
+ for (let j = 0; j < amountArr[i]; j++) {
+ // 遍历背包容量
+ for (let k = bagSize; k >= weightArr[i]; k--) {
+ dp[k] = Math.max(dp[k], dp[k - weightArr[i]] + valueArr[i]);
+ }
+ }
+ }
+ console.log(dp);
+}
+testMultiPack();
+```
+
+
+
-----------------------
From 871d96a2f9202504f2f5c754da7404f602a9f073 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 11 May 2022 16:48:59 +0800
Subject: [PATCH 043/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200209.=E9=95=BF?=
=?UTF-8?q?=E5=BA=A6=E6=9C=80=E5=B0=8F=E7=9A=84=E5=AD=90=E6=95=B0=E7=BB=84?=
=?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0209.长度最小的子数组.md | 48 +++++++++++++++++++++++++++++++
1 file changed, 48 insertions(+)
diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md
index fd72cf1b..78b8156c 100644
--- a/problems/0209.长度最小的子数组.md
+++ b/problems/0209.长度最小的子数组.md
@@ -400,6 +400,54 @@ class Solution {
}
}
```
+Scala:
+
+滑动窗口:
+```scala
+object Solution {
+ def minSubArrayLen(target: Int, nums: Array[Int]): Int = {
+ var result = Int.MaxValue // 返回结果,默认最大值
+ var left = 0 // 慢指针,当sum>=target,向右移动
+ var sum = 0 // 窗口值的总和
+ for (right <- 0 until nums.length) {
+ sum += nums(right)
+ while (sum >= target) {
+ result = math.min(result, right - left + 1) // 产生新结果
+ sum -= nums(left) // 左指针移动,窗口总和减去左指针的值
+ left += 1 // 左指针向右移动
+ }
+ }
+ // 相当于三元运算符,return关键字可以省略
+ if (result == Int.MaxValue) 0 else result
+ }
+}
+```
+
+暴力解法:
+```scala
+object Solution {
+ def minSubArrayLen(target: Int, nums: Array[Int]): Int = {
+ import scala.util.control.Breaks
+ var res = Int.MaxValue
+ var subLength = 0
+ for (i <- 0 until nums.length) {
+ var sum = 0
+ Breaks.breakable(
+ for (j <- i until nums.length) {
+ sum += nums(j)
+ if (sum >= target) {
+ subLength = j - i + 1
+ res = math.min(subLength, res)
+ Breaks.break()
+ }
+ }
+ )
+ }
+ // 相当于三元运算符
+ if (res == Int.MaxValue) 0 else res
+ }
+}
+```
-----------------------
From c363e9da86973e5dafaa5e765c9c6318b5eb9723 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Wed, 11 May 2022 16:59:05 +0800
Subject: [PATCH 044/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880198.?=
=?UTF-8?q?=E6=89=93=E5=AE=B6=E5=8A=AB=E8=88=8D.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0198.打家劫舍.md | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md
index dfe1f3a0..a828b9a9 100644
--- a/problems/0198.打家劫舍.md
+++ b/problems/0198.打家劫舍.md
@@ -189,6 +189,29 @@ const rob = nums => {
};
```
+TypeScript:
+
+```typescript
+function rob(nums: number[]): number {
+ /**
+ dp[i]: 前i个房屋能偷到的最大金额
+ dp[0]: nums[0];
+ dp[1]: max(nums[0], nums[1]);
+ ...
+ dp[i]: max(dp[i-1], dp[i-2]+nums[i]);
+ */
+ const length: number = nums.length;
+ if (length === 1) return nums[0];
+ const dp: number[] = [];
+ dp[0] = nums[0];
+ dp[1] = Math.max(nums[0], nums[1]);
+ for (let i = 2; i < length; i++) {
+ dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
+ }
+ return dp[length - 1];
+};
+```
+
From a8cfc460e7143e6b6d8486ad9e8d88e1c9759211 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 11 May 2022 17:37:12 +0800
Subject: [PATCH 045/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200059.=E8=9E=BA?=
=?UTF-8?q?=E6=97=8B=E7=9F=A9=E9=98=B5II.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0059.螺旋矩阵II.md | 51 +++++++++++++++++++++++++++++++++++++
1 file changed, 51 insertions(+)
diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md
index a7b19a34..f3b8e1ce 100644
--- a/problems/0059.螺旋矩阵II.md
+++ b/problems/0059.螺旋矩阵II.md
@@ -564,6 +564,57 @@ int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
return ans;
}
```
+Scala:
+```scala
+object Solution {
+ def generateMatrix(n: Int): Array[Array[Int]] = {
+ var res = Array.ofDim[Int](n, n) // 定义一个n*n的二维矩阵
+ var num = 1 // 标志当前到了哪个数字
+ var i = 0 // 横坐标
+ var j = 0 // 竖坐标
+ while (num <= n * n) {
+ // 向右:当j不越界,并且下一个要填的数字是空白时
+ while (j < n && res(i)(j) == 0) {
+ res(i)(j) = num // 当前坐标等于num
+ num += 1 // num++
+ j += 1 // 竖坐标+1
+ }
+ i += 1 // 下移一行
+ j -= 1 // 左移一列
+
+ // 剩下的都同上
+
+ // 向下
+ while (i < n && res(i)(j) == 0) {
+ res(i)(j) = num
+ num += 1
+ i += 1
+ }
+ i -= 1
+ j -= 1
+
+ // 向左
+ while (j >= 0 && res(i)(j) == 0) {
+ res(i)(j) = num
+ num += 1
+ j -= 1
+ }
+ i -= 1
+ j += 1
+
+ // 向上
+ while (i >= 0 && res(i)(j) == 0) {
+ res(i)(j) = num
+ num += 1
+ i -= 1
+ }
+ i += 1
+ j += 1
+ }
+ res
+ }
+}
+```
-----------------------
From 296485551542d296e27486e985406d7944f3aa9a Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Wed, 11 May 2022 18:35:43 +0800
Subject: [PATCH 046/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880213.?=
=?UTF-8?q?=E6=89=93=E5=AE=B6=E5=8A=AB=E8=88=8DII.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0213.打家劫舍II.md | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md
index 8e569e46..9e698d01 100644
--- a/problems/0213.打家劫舍II.md
+++ b/problems/0213.打家劫舍II.md
@@ -165,7 +165,30 @@ const robRange = (nums, start, end) => {
return dp[end]
}
```
+TypeScript:
+
+```typescript
+function rob(nums: number[]): number {
+ const length: number = nums.length;
+ if (length === 0) return 0;
+ if (length === 1) return nums[0];
+ return Math.max(robRange(nums, 0, length - 2),
+ robRange(nums, 1, length - 1));
+};
+function robRange(nums: number[], start: number, end: number): number {
+ if (start === end) return nums[start];
+ const dp: number[] = [];
+ dp[start] = nums[start];
+ dp[start + 1] = Math.max(nums[start], nums[start + 1]);
+ for (let i = start + 2; i <= end; i++) {
+ dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
+ }
+ return dp[end];
+}
+```
+
Go:
+
```go
// 打家劫舍Ⅱ 动态规划
// 时间复杂度O(n) 空间复杂度O(n)
From 558dc3343150b1a91a1f307c0bb1fcb881abcd20 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 11 May 2022 19:11:53 +0800
Subject: [PATCH 047/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E9=93=BE=E8=A1=A8?=
=?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md=20Scala=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/链表理论基础.md | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/problems/链表理论基础.md b/problems/链表理论基础.md
index 095282f5..9dddf1e2 100644
--- a/problems/链表理论基础.md
+++ b/problems/链表理论基础.md
@@ -210,6 +210,13 @@ type ListNode struct {
}
```
+Scala:
+```scala
+class ListNode(_x: Int = 0, _next: ListNode = null) {
+ var next: ListNode = _next
+ var x: Int = _x
+}
+```
-----------------------
From 8a562b7a2511b44705a6d9e28388738d6a452848 Mon Sep 17 00:00:00 2001
From: UndeadSheep
Date: Wed, 11 May 2022 19:44:09 +0800
Subject: [PATCH 048/162] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20=E5=93=88=E5=B8=8C?=
=?UTF-8?q?=E8=A1=A8=E9=83=A8=E5=88=86=E7=9A=84=20C#=E7=89=88?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0001.两数之和.md | 18 ++++++++++++++++++
problems/0202.快乐数.md | 23 +++++++++++++++++++++++
problems/0242.有效的字母异位词.md | 19 +++++++++++++++++++
problems/0349.两个数组的交集.md | 18 ++++++++++++++++++
problems/0383.赎金信.md | 17 +++++++++++++++++
problems/0454.四数相加II.md | 27 +++++++++++++++++++++++++++
6 files changed, 122 insertions(+)
diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md
index 9571a773..459a66ad 100644
--- a/problems/0001.两数之和.md
+++ b/problems/0001.两数之和.md
@@ -274,6 +274,24 @@ class Solution {
}
}
```
+C#:
+```csharp
+public class Solution {
+ public int[] TwoSum(int[] nums, int target) {
+ Dictionary dic= new Dictionary();
+ for(int i=0;i
diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md
index 741a735a..51a79aff 100644
--- a/problems/0202.快乐数.md
+++ b/problems/0202.快乐数.md
@@ -385,5 +385,28 @@ bool isHappy(int n){
return bHappy;
}
```
+
+C#:
+```csharp
+public class Solution {
+ private int getSum(int n) {
+ int sum = 0;
+ //每位数的换算
+ while (n > 0) {
+ sum += (n % 10) * (n % 10);
+ n /= 10;
+ }
+ return sum;
+ }
+ public bool IsHappy(int n) {
+ HashSet set = new HashSet();
+ while(n != 1 && !set.Contains(n)) { //判断避免循环
+ set.Add(n);
+ n = getSum(n);
+ }
+ return n == 1;
+ }
+}
+```
-----------------------
diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md
index 080166fd..878b2466 100644
--- a/problems/0242.有效的字母异位词.md
+++ b/problems/0242.有效的字母异位词.md
@@ -307,6 +307,25 @@ impl Solution {
}
}
```
+
+C#:
+```csharp
+ public bool IsAnagram(string s, string t) {
+ int sl=s.Length,tl=t.Length;
+ if(sl!=tl) return false;
+ int[] a = new int[26];
+ for(int i = 0; i < sl; i++){
+ a[s[i] - 'a']++;
+ a[t[i] - 'a']--;
+ }
+ foreach (int i in a)
+ {
+ if (i != 0)
+ return false;
+ }
+ return true;
+ }
+```
## 相关题目
* 383.赎金信
diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md
index 45f19b6e..7f8958d2 100644
--- a/problems/0349.两个数组的交集.md
+++ b/problems/0349.两个数组的交集.md
@@ -313,6 +313,24 @@ int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* re
}
```
+C#:
+```csharp
+ public int[] Intersection(int[] nums1, int[] nums2) {
+ if(nums1==null||nums1.Length==0||nums2==null||nums1.Length==0)
+ return new int[0]; //注意数组条件
+ HashSet one = Insert(nums1);
+ HashSet two = Insert(nums2);
+ one.IntersectWith(two);
+ return one.ToArray();
+ }
+ public HashSet Insert(int[] nums){
+ HashSet one = new HashSet();
+ foreach(int num in nums){
+ one.Add(num);
+ }
+ return one;
+ }
+```
## 相关题目
* 350.两个数组的交集 II
diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md
index 5d9e8295..6d6efc55 100644
--- a/problems/0383.赎金信.md
+++ b/problems/0383.赎金信.md
@@ -361,5 +361,22 @@ impl Solution {
}
```
+C#:
+```csharp
+public bool CanConstruct(string ransomNote, string magazine) {
+ if(ransomNote.Length > magazine.Length) return false;
+ int[] letters = new int[26];
+ foreach(char c in magazine){
+ letters[c-'a']++;
+ }
+ foreach(char c in ransomNote){
+ letters[c-'a']--;
+ if(letters[c-'a']<0){
+ return false;
+ }
+ }
+ return true;
+ }
+```
-----------------------
diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md
index a6cd413b..962fe7a5 100644
--- a/problems/0454.四数相加II.md
+++ b/problems/0454.四数相加II.md
@@ -318,5 +318,32 @@ impl Solution {
}
```
+C#:
+```csharp
+public int FourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
+ Dictionary dic = new Dictionary();
+ foreach(var i in nums1){
+ foreach(var j in nums2){
+ int sum = i + j;
+ if(dic.ContainsKey(sum)){
+ dic[sum]++;
+ }else{
+ dic.Add(sum, 1);
+ }
+
+ }
+ }
+ int res = 0;
+ foreach(var a in nums3){
+ foreach(var b in nums4){
+ int sum = a+b;
+ if(dic.TryGetValue(-sum, out var result)){
+ res += result;
+ }
+ }
+ }
+ return res;
+ }
+```
-----------------------
From ef8564a5930805ace91776c5648fa7110800c2d7 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 11 May 2022 19:51:07 +0800
Subject: [PATCH 049/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200203.=E7=A7=BB?=
=?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0.md=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0203.移除链表元素.md | 32 +++++++++++++++++++++++++++++++-
1 file changed, 31 insertions(+), 1 deletion(-)
diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md
index c34831b7..53230c0b 100644
--- a/problems/0203.移除链表元素.md
+++ b/problems/0203.移除链表元素.md
@@ -446,6 +446,36 @@ impl Solution {
}
}
```
-
+Scala:
+```scala
+/**
+ * Definition for singly-linked list.
+ * class ListNode(_x: Int = 0, _next: ListNode = null) {
+ * var next: ListNode = _next
+ * var x: Int = _x
+ * }
+ */
+object Solution {
+ def removeElements(head: ListNode, `val`: Int): ListNode = {
+ if (head == null) return head
+ var dummy = new ListNode(-1, head) // 定义虚拟头节点
+ var cur = head // cur 表示当前节点
+ var pre = dummy // pre 表示cur前一个节点
+ while (cur != null) {
+ if (cur.x == `val`) {
+ // 相等,就删除那么cur的前一个节点pre执行cur的下一个
+ pre.next = cur.next
+ } else {
+ // 不相等,pre就等于当前cur节点
+ pre = cur
+ }
+ // 向下迭代
+ cur = cur.next
+ }
+ // 最终返回dummy的下一个,就是链表的头
+ dummy.next
+ }
+}
+```
-----------------------
From 898016b8a98aa7eeb2445681e66f0302a79c28ae Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 11 May 2022 21:13:42 +0800
Subject: [PATCH 050/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200707.=E8=AE=BE?=
=?UTF-8?q?=E8=AE=A1=E9=93=BE=E8=A1=A8.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0707.设计链表.md | 68 +++++++++++++++++++++++++++++++++++++++
1 file changed, 68 insertions(+)
diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md
index 37ce15ad..dcdb53f4 100644
--- a/problems/0707.设计链表.md
+++ b/problems/0707.设计链表.md
@@ -1154,7 +1154,75 @@ class MyLinkedList {
}
```
+Scala:
+```scala
+class ListNode(_x: Int = 0, _next: ListNode = null) {
+ var next: ListNode = _next
+ var x: Int = _x
+}
+class MyLinkedList() {
+
+ var size = 0 // 链表尺寸
+ var dummy: ListNode = new ListNode(0) // 虚拟头节点
+
+ // 获取第index个节点的值
+ def get(index: Int): Int = {
+ if (index < 0 || index >= size) {
+ return -1;
+ }
+ var cur = dummy
+ for (i <- 0 to index) {
+ cur = cur.next
+ }
+ cur.x // 返回cur的值
+ }
+
+ // 在链表最前面插入一个节点
+ def addAtHead(`val`: Int) {
+ addAtIndex(0, `val`)
+ }
+
+ // 在链表最后面插入一个节点
+ def addAtTail(`val`: Int) {
+ addAtIndex(size, `val`)
+ }
+
+ // 在第index个节点之前插入一个新节点
+ // 如果index等于链表长度,则说明新插入的节点是尾巴
+ // 如果index等于0,则说明新插入的节点是头
+ // 如果index>链表长度,则说明为空
+ def addAtIndex(index: Int, `val`: Int) {
+ if (index > size) {
+ return
+ }
+ var loc = index // 因为参数index是val不可变类型,所以需要赋值给一个可变类型
+ if (index < 0) {
+ loc = 0
+ }
+ size += 1 //链表尺寸+1
+ var pre = dummy
+ for (i <- 0 until loc) {
+ pre = pre.next
+ }
+ val node: ListNode = new ListNode(`val`, pre.next)
+ pre.next = node
+ }
+ // 删除第index个节点
+ def deleteAtIndex(index: Int) {
+ if (index < 0 || index >= size) {
+ return
+ }
+ size -= 1
+ var pre = dummy
+ for (i <- 0 until index) {
+ pre = pre.next
+ }
+ pre.next = pre.next.next
+ }
+
+}
+```
-----------------------
From 923ce563f1461876fbed667f8a79194ccb060096 Mon Sep 17 00:00:00 2001
From: yangtzech
Date: Wed, 11 May 2022 21:30:43 +0800
Subject: [PATCH 051/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=EF=BC=880102.?=
=?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D?=
=?UTF-8?q?=E5=8E=86.md=EF=BC=89=EF=BC=9A102.=E4=BA=8C=E5=8F=89=E6=A0=91?=
=?UTF-8?q?=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=20=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0=20c++=20=E9=80=92=E5=BD=92=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index ab8f2e57..5f69f53d 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -82,6 +82,26 @@ public:
}
};
```
+```CPP
+# 递归法
+class Solution {
+public:
+ void order(TreeNode* cur, vector>& result, int depth)
+ {
+ if (cur == nullptr) return;
+ if (result.size() == depth) result.push_back(vector());
+ result[depth].push_back(cur->val);
+ order(cur->left, result, depth + 1);
+ order(cur->right, result, depth + 1);
+ }
+ vector> levelOrder(TreeNode* root) {
+ vector> result;
+ int depth = 0;
+ order(root, result, depth);
+ return result;
+ }
+};
+```
python3代码:
From 3606a624237334eddee98308e39daedbb2d250b0 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 11 May 2022 23:03:42 +0800
Subject: [PATCH 052/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200206.=E7=BF=BB?=
=?UTF-8?q?=E8=BD=AC=E9=93=BE=E8=A1=A8.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0206.翻转链表.md | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md
index 941928ba..25b16907 100644
--- a/problems/0206.翻转链表.md
+++ b/problems/0206.翻转链表.md
@@ -496,6 +496,40 @@ struct ListNode* reverseList(struct ListNode* head){
return reverse(NULL, head);
}
```
+Scala:
+双指针法:
+```scala
+object Solution {
+ def reverseList(head: ListNode): ListNode = {
+ var pre: ListNode = null
+ var cur = head
+ while (cur != null) {
+ var tmp = cur.next
+ cur.next = pre
+ pre = cur
+ cur = tmp
+ }
+ pre
+ }
+}
+```
+递归法:
+```scala
+object Solution {
+ def reverseList(head: ListNode): ListNode = {
+ reverse(null, head)
+ }
+
+ def reverse(pre: ListNode, cur: ListNode): ListNode = {
+ if (cur == null) {
+ return pre // 如果当前cur为空,则返回pre
+ }
+ val tmp: ListNode = cur.next
+ cur.next = pre
+ reverse(cur, tmp) // 此时cur成为前一个节点,tmp是当前节点
+ }
+}
+```
-----------------------
From 83086c903d77496e6fa34e7e4b0069e27ad1210c Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 12 May 2022 10:13:00 +0800
Subject: [PATCH 053/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200024.=E4=B8=A4?=
=?UTF-8?q?=E4=B8=A4=E4=BA=A4=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84?=
=?UTF-8?q?=E8=8A=82=E7=82=B9.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0024.两两交换链表中的节点.md | 24 +++++++++++++++++++++++-
1 file changed, 23 insertions(+), 1 deletion(-)
diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md
index ce75e0d7..2289c229 100644
--- a/problems/0024.两两交换链表中的节点.md
+++ b/problems/0024.两两交换链表中的节点.md
@@ -311,7 +311,29 @@ func swapPairs(_ head: ListNode?) -> ListNode? {
return dummyHead.next
}
```
-
+Scala:
+```scala
+// 虚拟头节点
+object Solution {
+ def swapPairs(head: ListNode): ListNode = {
+ var dummy = new ListNode(0, head) // 虚拟头节点
+ var pre = dummy
+ var cur = head
+ // 当pre的下一个和下下个都不为空,才进行两两转换
+ while (pre.next != null && pre.next.next != null) {
+ var tmp: ListNode = cur.next.next // 缓存下一次要进行转换的第一个节点
+ pre.next = cur.next // 步骤一
+ cur.next.next = cur // 步骤二
+ cur.next = tmp // 步骤三
+ // 下面是准备下一轮的交换
+ pre = cur
+ cur = tmp
+ }
+ // 最终返回dummy虚拟头节点的下一个,return可以省略
+ dummy.next
+ }
+}
+```
-----------------------
From 5fd85215ea9c30c73e5ab84f41dbc9cf170e8617 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 12 May 2022 10:53:20 +0800
Subject: [PATCH 054/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200019.=E5=88=A0?=
=?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=AC?=
=?UTF-8?q?N=E4=B8=AA=E8=8A=82=E7=82=B9.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0019.删除链表的倒数第N个节点.md | 24 +++++++++++++++++++++++-
1 file changed, 23 insertions(+), 1 deletion(-)
diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md
index 813e9b02..8df65627 100644
--- a/problems/0019.删除链表的倒数第N个节点.md
+++ b/problems/0019.删除链表的倒数第N个节点.md
@@ -289,6 +289,28 @@ func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
return dummyHead.next
}
```
-
+Scala:
+```scala
+object Solution {
+ def removeNthFromEnd(head: ListNode, n: Int): ListNode = {
+ val dummy = new ListNode(-1, head) // 定义虚拟头节点
+ var fast = head // 快指针从头开始走
+ var slow = dummy // 慢指针从虚拟头开始头
+ // 因为参数 n 是不可变量,所以不能使用 while(n>0){n-=1}的方式
+ for (i <- 0 until n) {
+ fast = fast.next
+ }
+ // 快指针和满指针一起走,直到fast走到null
+ while (fast != null) {
+ slow = slow.next
+ fast = fast.next
+ }
+ // 删除slow的下一个节点
+ slow.next = slow.next.next
+ // 返回虚拟头节点的下一个
+ dummy.next
+ }
+}
+```
-----------------------
From 6992735d8de6d1875d0565413faed410e81c822e Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 12 May 2022 12:46:47 +0800
Subject: [PATCH 055/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E9=9D=A2=E8=AF=95?=
=?UTF-8?q?=E9=A2=9802.07.=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4.md=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/面试题02.07.链表相交.md | 50 +++++++++++++++++++++++++++++++-
1 file changed, 49 insertions(+), 1 deletion(-)
diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md
index 2e7226de..0a38cc33 100644
--- a/problems/面试题02.07.链表相交.md
+++ b/problems/面试题02.07.链表相交.md
@@ -317,7 +317,55 @@ ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
}
```
-
+Scala:
+```scala
+object Solution {
+ def getIntersectionNode(headA: ListNode, headB: ListNode): ListNode = {
+ var lenA = 0 // headA链表的长度
+ var lenB = 0 // headB链表的长度
+ var tmp = headA // 临时变量
+ // 统计headA的长度
+ while (tmp != null) {
+ lenA += 1;
+ tmp = tmp.next
+ }
+ // 统计headB的长度
+ tmp = headB // 临时变量赋值给headB
+ while (tmp != null) {
+ lenB += 1
+ tmp = tmp.next
+ }
+ // 因为传递过来的参数是不可变量,所以需要重新定义
+ var listA = headA
+ var listB = headB
+ // 两个链表的长度差
+ // 如果gap>0,lenA>lenB,headA(listA)链表往前移动gap步
+ // 如果gap<0,lenA 0) {
+ // 因为不可以i-=1,所以可以使用for
+ for (i <- 0 until gap) {
+ listA = listA.next // 链表headA(listA) 移动
+ }
+ } else {
+ gap = math.abs(gap) // 此刻gap为负值,取绝对值
+ for (i <- 0 until gap) {
+ listB = listB.next
+ }
+ }
+ // 现在两个链表同时往前走,如果相等则返回
+ while (listA != null && listB != null) {
+ if (listA == listB) {
+ return listA
+ }
+ listA = listA.next
+ listB = listB.next
+ }
+ // 如果链表没有相交则返回null,return可以省略
+ null
+ }
+}
+```
-----------------------
From 2ce58ac6756775f8ec5139b36a23e8f3de232d30 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 12 May 2022 12:55:14 +0800
Subject: [PATCH 056/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880337.?=
=?UTF-8?q?=E6=89=93=E5=AE=B6=E5=8A=AB=E8=88=8DIII.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0337.打家劫舍III.md | 43 ++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+)
diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md
index a4d8f6b2..6f50723d 100644
--- a/problems/0337.打家劫舍III.md
+++ b/problems/0337.打家劫舍III.md
@@ -429,7 +429,50 @@ const rob = root => {
};
```
+### TypeScript
+
+> 记忆化后序遍历
+
+```typescript
+const memory: Map = new Map();
+function rob(root: TreeNode | null): number {
+ if (root === null) return 0;
+ if (memory.has(root)) return memory.get(root);
+ // 不取当前节点
+ const res1: number = rob(root.left) + rob(root.right);
+ // 取当前节点
+ let res2: number = root.val;
+ if (root.left !== null) res2 += rob(root.left.left) + rob(root.left.right);
+ if (root.right !== null) res2 += rob(root.right.left) + rob(root.right.right);
+ const res: number = Math.max(res1, res2);
+ memory.set(root, res);
+ return res;
+};
+```
+
+> 状态标记化后序遍历
+
+```typescript
+function rob(root: TreeNode | null): number {
+ return Math.max(...robNode(root));
+};
+// [0]-不偷当前节点能获得的最大金额; [1]-偷~~
+type MaxValueArr = [number, number];
+function robNode(node: TreeNode | null): MaxValueArr {
+ if (node === null) return [0, 0];
+ const leftArr: MaxValueArr = robNode(node.left);
+ const rightArr: MaxValueArr = robNode(node.right);
+ // 不偷
+ const val1: number = Math.max(leftArr[0], leftArr[1]) +
+ Math.max(rightArr[0], rightArr[1]);
+ // 偷
+ const val2: number = leftArr[0] + rightArr[0] + node.val;
+ return [val1, val2];
+}
+```
+
### Go
+
```go
// 打家劫舍Ⅲ 动态规划
// 时间复杂度O(n) 空间复杂度O(logn)
From 5627d4ba8605f35b8d63cf4af363c64d721f69a3 Mon Sep 17 00:00:00 2001
From: Jamcy123 <1219502823@qq.com>
Date: Thu, 12 May 2022 16:04:42 +0800
Subject: [PATCH 057/162] =?UTF-8?q?=E8=83=8C=E5=8C=85=E7=90=86=E8=AE=BA?=
=?UTF-8?q?=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-1=20js=20=E7=89=88?=
=?UTF-8?q?=E6=9C=AC=E4=BF=AE=E6=94=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/背包理论基础01背包-1.md | 51 ++++++++++++--------------------
1 file changed, 19 insertions(+), 32 deletions(-)
diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md
index fe940b4c..e833ea80 100644
--- a/problems/背包理论基础01背包-1.md
+++ b/problems/背包理论基础01背包-1.md
@@ -380,44 +380,31 @@ func main() {
### javascript
```js
-function testweightbagproblem (wight, value, size) {
- const len = wight.length,
- dp = array.from({length: len + 1}).map(
- () => array(size + 1).fill(0)
- );
-
- for(let i = 1; i <= len; i++) {
- for(let j = 0; j <= size; j++) {
- if(wight[i - 1] <= j) {
- dp[i][j] = math.max(
- dp[i - 1][j],
- value[i - 1] + dp[i - 1][j - wight[i - 1]]
- )
- } else {
- dp[i][j] = dp[i - 1][j];
- }
+function testWeightBagProblem (weight, value, size) {
+ // 定义 dp 数组
+ const len = weight.length,
+ dp = Array(len).fill().map(() => Array(size + 1).fill(0));
+
+ // 初始化
+ for(let j = weight[0]; j <= size; j++) {
+ dp[0][j] = value[0];
}
- }
-// console.table(dp);
-
- return dp[len][size];
-}
-
-function testWeightBagProblem2 (wight, value, size) {
- const len = wight.length,
- dp = Array(size + 1).fill(0);
- for(let i = 1; i <= len; i++) {
- for(let j = size; j >= wight[i - 1]; j--) {
- dp[j] = Math.max(dp[j], value[i - 1] + dp[j - wight[i - 1]]);
+ // weight 数组的长度len 就是物品个数
+ for(let i = 1; i < len; i++) { // 遍历物品
+ for(let j = 0; j <= size; j++) { // 遍历背包容量
+ if(j < weight[i]) dp[i][j] = dp[i - 1][j];
+ else dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
+ }
}
- }
- return dp[size];
-}
+ console.table(dp)
+
+ return dp[len - 1][size];
+}
function test () {
- console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6));
+ console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6));
}
test();
From 40457f0f44d3981dc071fd56871f66d7e5946af1 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 12 May 2022 16:16:48 +0800
Subject: [PATCH 058/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880121.?=
=?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3?=
=?UTF-8?q?=E6=97=B6=E6=9C=BA.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?=
=?UTF-8?q?ript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0121.买卖股票的最佳时机.md | 40 +++++++++++++++++++++++++++++
1 file changed, 40 insertions(+)
diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md
index f0bc3b97..a2498bb6 100644
--- a/problems/0121.买卖股票的最佳时机.md
+++ b/problems/0121.买卖股票的最佳时机.md
@@ -426,6 +426,46 @@ var maxProfit = function(prices) {
};
```
+TypeScript:
+
+> 贪心法
+
+```typescript
+function maxProfit(prices: number[]): number {
+ if (prices.length === 0) return 0;
+ let buy: number = prices[0];
+ let profitMax: number = 0;
+ for (let i = 1, length = prices.length; i < length; i++) {
+ profitMax = Math.max(profitMax, prices[i] - buy);
+ buy = Math.min(prices[i], buy);
+ }
+ return profitMax;
+};
+```
+
+> 动态规划
+
+```typescript
+function maxProfit(prices: number[]): number {
+ /**
+ dp[i][0]: 第i天持有股票的最大现金
+ dp[i][1]: 第i天不持有股票的最大现金
+ */
+ const length = prices.length;
+ if (length === 0) return 0;
+ const dp: number[][] = [];
+ dp[0] = [-prices[0], 0];
+ for (let i = 1; i < length; i++) {
+ dp[i] = [];
+ dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
+ dp[i][1] = Math.max(dp[i - 1][0] + prices[i], dp[i - 1][1]);
+ }
+ return dp[length - 1][1];
+};
+```
+
+
+
-----------------------
From 8ba775d04acd100e6cdac8ebd913aaead67fae15 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 12 May 2022 16:40:54 +0800
Subject: [PATCH 059/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880122.?=
=?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3?=
=?UTF-8?q?=E6=97=B6=E6=9C=BAII=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92.md?=
=?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../0122.买卖股票的最佳时机II(动态规划).md | 36 +++++++++++++++++++
1 file changed, 36 insertions(+)
diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md
index 5a165a14..12b21fde 100644
--- a/problems/0122.买卖股票的最佳时机II(动态规划).md
+++ b/problems/0122.买卖股票的最佳时机II(动态规划).md
@@ -295,6 +295,42 @@ const maxProfit = (prices) => {
}
```
+TypeScript:
+
+> 动态规划
+
+```typescript
+function maxProfit(prices: number[]): number {
+ /**
+ dp[i][0]: 第i天持有股票
+ dp[i][1]: 第i天不持有股票
+ */
+ const length: number = prices.length;
+ if (length === 0) return 0;
+ const dp: number[][] = new Array(length).fill(0).map(_ => []);
+ dp[0] = [-prices[0], 0];
+ for (let i = 1; i < length; i++) {
+ dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
+ dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
+ }
+ return dp[length - 1][1];
+};
+```
+
+> 贪心法
+
+```typescript
+function maxProfit(prices: number[]): number {
+ let resProfit: number = 0;
+ for (let i = 1, length = prices.length; i < length; i++) {
+ if (prices[i] > prices[i - 1]) {
+ resProfit += prices[i] - prices[i - 1];
+ }
+ }
+ return resProfit;
+};
+```
+
-----------------------
From 0a58ef986de4c20c5d69a4b490b478f44b7f3f5c Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 12 May 2022 17:35:30 +0800
Subject: [PATCH 060/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200142.=E7=8E=AF?=
=?UTF-8?q?=E5=BD=A2=E9=93=BE=E8=A1=A8II.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0142.环形链表II.md | 26 +++++++++++++++++++++++++-
1 file changed, 25 insertions(+), 1 deletion(-)
diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md
index e8ca950d..f8e62d45 100644
--- a/problems/0142.环形链表II.md
+++ b/problems/0142.环形链表II.md
@@ -370,7 +370,31 @@ ListNode *detectCycle(ListNode *head) {
}
```
-
+Scala:
+```scala
+object Solution {
+ def detectCycle(head: ListNode): ListNode = {
+ var fast = head // 快指针
+ var slow = head // 慢指针
+ while (fast != null && fast.next != null) {
+ fast = fast.next.next // 快指针一次走两步
+ slow = slow.next // 慢指针一次走一步
+ // 如果相遇,fast快指针回到头
+ if (fast == slow) {
+ fast = head
+ // 两个指针一步一步的走,第一次相遇的节点必是入环节点
+ while (fast != slow) {
+ fast = fast.next
+ slow = slow.next
+ }
+ return fast
+ }
+ }
+ // 如果fast指向空值,必然无环返回null
+ null
+ }
+}
+```
-----------------------
From a25409d7ec351aaf2e6e513e3e091fc97cd17d60 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 12 May 2022 19:16:20 +0800
Subject: [PATCH 061/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200242.=E6=9C=89?=
=?UTF-8?q?=E6=95=88=E7=9A=84=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D?=
=?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0242.有效的字母异位词.md | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md
index 080166fd..4f0d143e 100644
--- a/problems/0242.有效的字母异位词.md
+++ b/problems/0242.有效的字母异位词.md
@@ -307,6 +307,31 @@ impl Solution {
}
}
```
+
+Scala:
+```scala
+object Solution {
+ def isAnagram(s: String, t: String): Boolean = {
+ // 如果两个字符串的长度不等,直接返回false
+ if (s.length != t.length) return false
+ val record = new Array[Int](26) // 记录每个单词出现了多少次
+ // 遍历字符串,对于s字符串单词对应的记录+=1,t字符串对应的记录-=1
+ for (i <- 0 until s.length) {
+ record(s(i) - 97) += 1
+ record(t(i) - 97) -= 1
+ }
+ // 如果不等于则直接返回false
+ for (i <- 0 until 26) {
+ if (record(i) != 0) {
+ return false
+ }
+ }
+ // 如果前面不返回false,说明匹配成功,返回true,return可以省略
+ true
+ }
+}
+```
+
## 相关题目
* 383.赎金信
From 74b76bfd120446653495d96135e697b5797bae35 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 12 May 2022 22:21:29 +0800
Subject: [PATCH 062/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=201002.=E6=9F=A5?=
=?UTF-8?q?=E6=89=BE=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6.md=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/1002.查找常用字符.md | 34 +++++++++++++++++++++++++++++++++-
1 file changed, 33 insertions(+), 1 deletion(-)
diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md
index 36937b0b..075b5ef1 100644
--- a/problems/1002.查找常用字符.md
+++ b/problems/1002.查找常用字符.md
@@ -418,6 +418,38 @@ char ** commonChars(char ** words, int wordsSize, int* returnSize){
return ret;
}
```
-
+Scala:
+```scala
+object Solution {
+ def commonChars(words: Array[String]): List[String] = {
+ // 声明返回结果的不可变List集合,因为res要重新赋值,所以声明为var
+ var res = List[String]()
+ var hash = new Array[Int](26) // 统计字符出现的最小频率
+ // 统计第一个字符串中字符出现的次数
+ for (i <- 0 until words(0).length) {
+ hash(words(0)(i) - 'a') += 1
+ }
+ // 统计其他字符串出现的频率
+ for (i <- 1 until words.length) {
+ // 统计其他字符出现的频率
+ var hashOtherStr = new Array[Int](26)
+ for (j <- 0 until words(i).length) {
+ hashOtherStr(words(i)(j) - 'a') += 1
+ }
+ // 更新hash,取26个字母最小出现的频率
+ for (k <- 0 until 26) {
+ hash(k) = math.min(hash(k), hashOtherStr(k))
+ }
+ }
+ // 根据hash的结果转换输出的形式
+ for (i <- 0 until 26) {
+ for (j <- 0 until hash(i)) {
+ res = res :+ (i + 'a').toChar.toString
+ }
+ }
+ res
+ }
+}
+```
-----------------------
From a71f7d2127bae83cc42dffd20b4c460865006d15 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 12 May 2022 23:23:59 +0800
Subject: [PATCH 063/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880123.?=
=?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3?=
=?UTF-8?q?=E6=97=B6=E6=9C=BAIII.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typ?=
=?UTF-8?q?escript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0123.买卖股票的最佳时机III.md | 30 ++++++++++++++++++++++++++
1 file changed, 30 insertions(+)
diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md
index 56ade343..67c99497 100644
--- a/problems/0123.买卖股票的最佳时机III.md
+++ b/problems/0123.买卖股票的最佳时机III.md
@@ -352,6 +352,36 @@ const maxProfit = prices => {
};
```
+TypeScript:
+
+> 版本一
+
+```typescript
+function maxProfit(prices: number[]): number {
+ /**
+ dp[i][0]: 无操作;
+ dp[i][1]: 第一次买入;
+ dp[i][2]: 第一次卖出;
+ dp[i][3]: 第二次买入;
+ dp[i][4]: 第二次卖出;
+ */
+ const length: number = prices.length;
+ if (length === 0) return 0;
+ const dp: number[][] = new Array(length).fill(0)
+ .map(_ => new Array(5).fill(0));
+ dp[0][1] = -prices[0];
+ dp[0][3] = -prices[0];
+ for (let i = 1; i < length; i++) {
+ dp[i][0] = dp[i - 1][0];
+ dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
+ dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
+ dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
+ dp[i][4] = Math.max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
+ }
+ return Math.max(dp[length - 1][2], dp[length - 1][4]);
+};
+```
+
Go:
> 版本一:
From 78c6602ff20c309132007795956f332d66ff7130 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 13 May 2022 10:05:27 +0800
Subject: [PATCH 064/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200349.=E4=B8=A4?=
=?UTF-8?q?=E4=B8=AA=E6=95=B0=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86.md=20Sca?=
=?UTF-8?q?la=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0349.两个数组的交集.md | 42 +++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md
index 45f19b6e..49cf4112 100644
--- a/problems/0349.两个数组的交集.md
+++ b/problems/0349.两个数组的交集.md
@@ -312,7 +312,49 @@ int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* re
return result;
}
```
+Scala:
+正常解法:
+```scala
+object Solution {
+ def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = {
+ // 导入mutable
+ import scala.collection.mutable
+ // 临时Set,用于记录数组1出现的每个元素
+ val tmpSet: mutable.HashSet[Int] = new mutable.HashSet[Int]()
+ // 结果Set,存储最终结果
+ val resSet: mutable.HashSet[Int] = new mutable.HashSet[Int]()
+ // 遍历nums1,把每个元素添加到tmpSet
+ nums1.foreach(tmpSet.add(_))
+ // 遍历nums2,如果在tmpSet存在就添加到resSet
+ nums2.foreach(elem => {
+ if (tmpSet.contains(elem)) {
+ resSet.add(elem)
+ }
+ })
+ // 将结果转换为Array返回,return可以省略
+ resSet.toArray
+ }
+}
+```
+骚操作1:
+```scala
+object Solution {
+ def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = {
+ // 先转为Set,然后取交集,最后转换为Array
+ (nums1.toSet).intersect(nums2.toSet).toArray
+ }
+}
+```
+骚操作2:
+```scala
+object Solution {
+ def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = {
+ // distinct去重,然后取交集
+ (nums1.distinct).intersect(nums2.distinct)
+ }
+}
+```
## 相关题目
* 350.两个数组的交集 II
From 9f720470e8e2360047052897885261545d0e1ac7 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 13 May 2022 10:29:17 +0800
Subject: [PATCH 065/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200202.=E5=BF=AB?=
=?UTF-8?q?=E4=B9=90=E6=95=B0.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0202.快乐数.md | 33 +++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md
index 741a735a..2d0f7d27 100644
--- a/problems/0202.快乐数.md
+++ b/problems/0202.快乐数.md
@@ -385,5 +385,38 @@ bool isHappy(int n){
return bHappy;
}
```
+Scala:
+```scala
+object Solution {
+ // 引入mutable
+ import scala.collection.mutable
+ def isHappy(n: Int): Boolean = {
+ // 存放每次计算后的结果
+ val set: mutable.HashSet[Int] = new mutable.HashSet[Int]()
+ var tmp = n // 因为形参是不可变量,所以需要找到一个临时变量
+ // 开始进入循环
+ while (true) {
+ val sum = getSum(tmp) // 获取这个数每个值的平方和
+ if (sum == 1) return true // 如果最终等于 1,则返回true
+ // 如果set里面已经有这个值了,说明进入无限循环,可以返回false,否则添加这个值到set
+ if (set.contains(sum)) return false
+ else set.add(sum)
+ tmp = sum
+ }
+ // 最终需要返回值,直接返回个false
+ false
+ }
+
+ def getSum(n: Int): Int = {
+ var sum = 0
+ var tmp = n
+ while (tmp != 0) {
+ sum += (tmp % 10) * (tmp % 10)
+ tmp = tmp / 10
+ }
+ sum
+ }
+}
+```
-----------------------
From be5cc136c56cb194af8ce1d794871ca7af4b1e1d Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 13 May 2022 11:00:11 +0800
Subject: [PATCH 066/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200035.=E6=90=9C?=
=?UTF-8?q?=E7=B4=A2=E6=8F=92=E5=85=A5=E4=BD=8D=E7=BD=AE.md=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0035.搜索插入位置.md | 21 ++++++++++++++++++++-
1 file changed, 20 insertions(+), 1 deletion(-)
diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md
index 9a770703..3e8cf5c8 100644
--- a/problems/0035.搜索插入位置.md
+++ b/problems/0035.搜索插入位置.md
@@ -316,7 +316,26 @@ func searchInsert(_ nums: [Int], _ target: Int) -> Int {
return right + 1
}
```
-
+### Scala
+```scala
+object Solution {
+ def searchInsert(nums: Array[Int], target: Int): Int = {
+ var left = 0
+ var right = nums.length - 1
+ while (left <= right) {
+ var mid = left + (right - left) / 2
+ if (target == nums(mid)) {
+ return mid
+ } else if (target > nums(mid)) {
+ left = mid + 1
+ } else {
+ right = mid - 1
+ }
+ }
+ right + 1
+ }
+}
+```
From 95593634b341a951850fae3b5aa739ba7c5d3864 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 13 May 2022 11:01:04 +0800
Subject: [PATCH 067/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200704.=E4=BA=8C?=
=?UTF-8?q?=E5=88=86=E6=9F=A5=E6=89=BE.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0704.二分查找.md | 41 +++++++++++++++++++++++++++++++++++++++
1 file changed, 41 insertions(+)
diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md
index 55625130..1e474f9a 100644
--- a/problems/0704.二分查找.md
+++ b/problems/0704.二分查找.md
@@ -610,7 +610,48 @@ public class Solution{
}
}
```
+**Scala:**
+(版本一)左闭右闭区间
+```scala
+object Solution {
+ def search(nums: Array[Int], target: Int): Int = {
+ var left = 0
+ var right = nums.length - 1
+ while (left <= right) {
+ var mid = left + ((right - left) / 2)
+ if (target == nums(mid)) {
+ return mid
+ } else if (target < nums(mid)) {
+ right = mid - 1
+ } else {
+ left = mid + 1
+ }
+ }
+ -1
+ }
+}
+```
+(版本二)左闭右开区间
+```scala
+object Solution {
+ def search(nums: Array[Int], target: Int): Int = {
+ var left = 0
+ var right = nums.length
+ while (left < right) {
+ val mid = left + (right - left) / 2
+ if (target == nums(mid)) {
+ return mid
+ } else if (target < nums(mid)) {
+ right = mid
+ } else {
+ left = mid + 1
+ }
+ }
+ -1
+ }
+}
+```
-----------------------
From 9fc232aba413b43fd479ad5b4fd1a186ff90a359 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 13 May 2022 11:01:45 +0800
Subject: [PATCH 068/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200034.=E5=9C=A8?=
=?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84=E4=B8=AD=E6=9F=A5=E6=89=BE?=
=?UTF-8?q?=E5=85=83=E7=B4=A0=E7=9A=84=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=92=8C?=
=?UTF-8?q?=E6=9C=80=E5=90=8E=E4=B8=80=E4=B8=AA=E4=BD=8D=E7=BD=AE.md=20Sca?=
=?UTF-8?q?la=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
...排序数组中查找元素的第一个和最后一个位置.md | 45 +++++++++++++++++++
1 file changed, 45 insertions(+)
diff --git a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md
index dfd90b82..260462c2 100644
--- a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md
+++ b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md
@@ -480,7 +480,52 @@ var searchRange = function(nums, target) {
return [-1, -1];
};
```
+### Scala
+```scala
+object Solution {
+ def searchRange(nums: Array[Int], target: Int): Array[Int] = {
+ var left = getLeftBorder(nums, target)
+ var right = getRightBorder(nums, target)
+ if (left == -2 || right == -2) return Array(-1, -1)
+ if (right - left > 1) return Array(left + 1, right - 1)
+ Array(-1, -1)
+ }
+ // 寻找左边界
+ def getLeftBorder(nums: Array[Int], target: Int): Int = {
+ var leftBorder = -2
+ var left = 0
+ var right = nums.length - 1
+ while (left <= right) {
+ var mid = left + (right - left) / 2
+ if (nums(mid) >= target) {
+ right = mid - 1
+ leftBorder = right
+ } else {
+ left = mid + 1
+ }
+ }
+ leftBorder
+ }
+
+ // 寻找右边界
+ def getRightBorder(nums: Array[Int], target: Int): Int = {
+ var rightBorder = -2
+ var left = 0
+ var right = nums.length - 1
+ while (left <= right) {
+ var mid = left + (right - left) / 2
+ if (nums(mid) <= target) {
+ left = mid + 1
+ rightBorder = left
+ } else {
+ right = mid - 1
+ }
+ }
+ rightBorder
+ }
+}
+```
-----------------------
From f131f27744693b91f40df4ea0fb7c1578bd6647b Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 13 May 2022 11:02:19 +0800
Subject: [PATCH 069/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200027.=E7=A7=BB?=
=?UTF-8?q?=E9=99=A4=E5=85=83=E7=B4=A0.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0027.移除元素.md | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md
index 590cf0b9..5ff327fb 100644
--- a/problems/0027.移除元素.md
+++ b/problems/0027.移除元素.md
@@ -328,6 +328,20 @@ int removeElement(int* nums, int numsSize, int val){
return slow;
}
```
-
+Scala:
+```scala
+object Solution {
+ def removeElement(nums: Array[Int], `val`: Int): Int = {
+ var slow = 0
+ for (fast <- 0 until nums.length) {
+ if (`val` != nums(fast)) {
+ nums(slow) = nums(fast)
+ slow += 1
+ }
+ }
+ slow
+ }
+}
+```
-----------------------
From 495998e509527b53a8b84cc0527dfcff4fc1e1af Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Fri, 13 May 2022 12:07:52 +0800
Subject: [PATCH 070/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880188.?=
=?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3?=
=?UTF-8?q?=E6=97=B6=E6=9C=BAIV.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0type?=
=?UTF-8?q?script=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0188.买卖股票的最佳时机IV.md | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md
index 61c558a1..27eb38c3 100644
--- a/problems/0188.买卖股票的最佳时机IV.md
+++ b/problems/0188.买卖股票的最佳时机IV.md
@@ -409,5 +409,27 @@ var maxProfit = function(k, prices) {
};
```
+TypeScript:
+
+```typescript
+function maxProfit(k: number, prices: number[]): number {
+ const length: number = prices.length;
+ if (length === 0) return 0;
+ const dp: number[][] = new Array(length).fill(0)
+ .map(_ => new Array(k * 2 + 1).fill(0));
+ for (let i = 1; i <= k; i++) {
+ dp[0][i * 2 - 1] = -prices[0];
+ }
+ for (let i = 1; i < length; i++) {
+ for (let j = 1; j < 2 * k + 1; j++) {
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] + Math.pow(-1, j) * prices[i]);
+ }
+ }
+ return dp[length - 1][2 * k];
+};
+```
+
+
+
-----------------------
From 127986e03a0b4acdedf80a6b38d3ded7d61514f3 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Fri, 13 May 2022 16:19:59 +0800
Subject: [PATCH 071/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880309.?=
=?UTF-8?q?=E6=9C=80=E4=BD=B3=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E6=97=B6?=
=?UTF-8?q?=E6=9C=BA=E5=90=AB=E5=86=B7=E5=86=BB=E6=9C=9F.md=EF=BC=89?=
=?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0309.最佳买卖股票时机含冷冻期.md | 60 +++++++++++++++++++++++
1 file changed, 60 insertions(+)
diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md
index f3e7541b..f037fe85 100644
--- a/problems/0309.最佳买卖股票时机含冷冻期.md
+++ b/problems/0309.最佳买卖股票时机含冷冻期.md
@@ -325,6 +325,66 @@ const maxProfit = (prices) => {
};
```
+TypeScript:
+
+> 版本一,与本文思路一致
+
+```typescript
+function maxProfit(prices: number[]): number {
+ /**
+ dp[i][0]: 持股状态;
+ dp[i][1]: 无股状态,当天为非冷冻期;
+ dp[i][2]: 无股状态,当天卖出;
+ dp[i][3]: 无股状态,当天为冷冻期;
+ */
+ const length: number = prices.length;
+ const dp: number[][] = new Array(length).fill(0).map(_ => []);
+ dp[0][0] = -prices[0];
+ dp[0][1] = dp[0][2] = dp[0][3] = 0;
+ for (let i = 1; i < length; i++) {
+ dp[i][0] = Math.max(
+ dp[i - 1][0],
+ Math.max(dp[i - 1][1], dp[i - 1][3]) - prices[i]
+ );
+ dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][3]);
+ dp[i][2] = dp[i - 1][0] + prices[i];
+ dp[i][3] = dp[i - 1][2];
+ }
+ const lastEl: number[] = dp[length - 1];
+ return Math.max(lastEl[1], lastEl[2], lastEl[3]);
+};
+```
+
+> 版本二,状态定义略有不同,可以帮助理解
+
+```typescript
+function maxProfit(prices: number[]): number {
+ /**
+ dp[i][0]: 持股状态,当天买入;
+ dp[i][1]: 持股状态,当天未买入;
+ dp[i][2]: 无股状态,当天卖出;
+ dp[i][3]: 无股状态,当天未卖出;
+
+ 买入有冷冻期限制,其实就是状态[0]只能由前一天的状态[3]得到;
+ 如果卖出有冷冻期限制,其实就是[2]由[1]得到。
+ */
+ const length: number = prices.length;
+ const dp: number[][] = new Array(length).fill(0).map(_ => []);
+ dp[0][0] = -prices[0];
+ dp[0][1] = -Infinity;
+ dp[0][2] = dp[0][3] = 0;
+ for (let i = 1; i < length; i++) {
+ dp[i][0] = dp[i - 1][3] - prices[i];
+ dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0]);
+ dp[i][2] = Math.max(dp[i - 1][0], dp[i - 1][1]) + prices[i];
+ dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2]);
+ }
+ return Math.max(dp[length - 1][2], dp[length - 1][3]);
+};
+```
+
+
+
-----------------------
From abe00238f44718c49b9442c26e7f7b01f84be3e4 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 13 May 2022 16:37:39 +0800
Subject: [PATCH 072/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200001.=E4=B8=A4?=
=?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0001.两数之和.md | 23 ++++++++++++++++++++++-
1 file changed, 22 insertions(+), 1 deletion(-)
diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md
index 9571a773..141e66f3 100644
--- a/problems/0001.两数之和.md
+++ b/problems/0001.两数之和.md
@@ -274,6 +274,27 @@ class Solution {
}
}
```
-
+Scala:
+```scala
+object Solution {
+ // 导入包
+ import scala.collection.mutable
+ def twoSum(nums: Array[Int], target: Int): Array[Int] = {
+ // key存储值,value存储下标
+ val map = new mutable.HashMap[Int, Int]()
+ for (i <- nums.indices) {
+ val tmp = target - nums(i) // 计算差值
+ // 如果这个差值存在于map,则说明找到了结果
+ if (map.contains(tmp)) {
+ return Array(map.get(tmp).get, i)
+ }
+ // 如果不包含把当前值与其下标放到map
+ map.put(nums(i), i)
+ }
+ // 如果没有找到直接返回一个空的数组,return关键字可以省略
+ new Array[Int](2)
+ }
+}
+```
-----------------------
From 53379c023fe935398801f41aad3dd0399b2d7d73 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 13 May 2022 17:28:14 +0800
Subject: [PATCH 073/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200454.=E5=9B=9B?=
=?UTF-8?q?=E6=95=B0=E7=9B=B8=E5=8A=A0II.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0454.四数相加II.md | 36 ++++++++++++++++++++++++++++++++++++
1 file changed, 36 insertions(+)
diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md
index a6cd413b..d4aba8fa 100644
--- a/problems/0454.四数相加II.md
+++ b/problems/0454.四数相加II.md
@@ -318,5 +318,41 @@ impl Solution {
}
```
+Scala:
+```scala
+object Solution {
+ // 导包
+ import scala.collection.mutable
+ def fourSumCount(nums1: Array[Int], nums2: Array[Int], nums3: Array[Int], nums4: Array[Int]): Int = {
+ // 定义一个HashMap,key存储值,value存储该值出现的次数
+ val map = new mutable.HashMap[Int, Int]()
+ // 遍历前两个数组,把他们所有可能的情况都记录到map
+ for (i <- nums1.indices) {
+ for (j <- nums2.indices) {
+ val tmp = nums1(i) + nums2(j)
+ // 如果包含该值,则对他的key加1,不包含则添加进去
+ if (map.contains(tmp)) {
+ map.put(tmp, map.get(tmp).get + 1)
+ } else {
+ map.put(tmp, 1)
+ }
+ }
+ }
+ var res = 0 // 结果变量
+ // 遍历后两个数组
+ for (i <- nums3.indices) {
+ for (j <- nums4.indices) {
+ val tmp = -(nums3(i) + nums4(j))
+ // 如果map中存在该值,结果就+=value
+ if (map.contains(tmp)) {
+ res += map.get(tmp).get
+ }
+ }
+ }
+ // 返回最终结果,可以省略关键字return
+ res
+ }
+}
+```
-----------------------
From 6c0d4365c6ed1e9a47c5f31e14d59912648f4afa Mon Sep 17 00:00:00 2001
From: lizhendong128
Date: Fri, 13 May 2022 17:26:03 +0800
Subject: [PATCH 074/162] =?UTF-8?q?=E4=BF=AE=E6=94=B90059=E8=9E=BA?=
=?UTF-8?q?=E6=97=8B=E7=9F=A9=E9=98=B5II=20Java=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
精简Java代码中不必要的变量,调整结构,减少代码量,使代码更加易读
---
problems/0059.螺旋矩阵II.md | 44 ++++++++++---------------------------
1 file changed, 12 insertions(+), 32 deletions(-)
diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md
index 93735895..7afc1575 100644
--- a/problems/0059.螺旋矩阵II.md
+++ b/problems/0059.螺旋矩阵II.md
@@ -130,57 +130,37 @@ Java:
```Java
class Solution {
public int[][] generateMatrix(int n) {
+ int loop = 0; // 控制循环次数
int[][] res = new int[n][n];
+ int start = 0; // 每次循环的开始点(start, start)
+ int count = 1; // 定义填充数字
+ int i, j;
- // 循环次数
- int loop = n / 2;
-
- // 定义每次循环起始位置
- int startX = 0;
- int startY = 0;
-
- // 定义偏移量
- int offset = 1;
-
- // 定义填充数字
- int count = 1;
-
- // 定义中间位置
- int mid = n / 2;
- while (loop > 0) {
- int i = startX;
- int j = startY;
-
+ while (loop++ < n / 2) { // 判断边界后,loop从1开始
// 模拟上侧从左到右
- for (; j startY; j--) {
+ for (; j >= loop; j--) {
res[i][j] = count++;
}
// 模拟左侧从下到上
- for (; i > startX; i--) {
+ for (; i >= loop; i--) {
res[i][j] = count++;
}
-
- loop--;
-
- startX += 1;
- startY += 1;
-
- offset += 2;
+ start++;
}
if (n % 2 == 1) {
- res[mid][mid] = count;
+ res[start][start] = count;
}
return res;
From 16c6abff54ec4b85d0891ed12914f538da7b8332 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 13 May 2022 21:02:07 +0800
Subject: [PATCH 075/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200383.=E8=B5=8E?=
=?UTF-8?q?=E9=87=91=E4=BF=A1.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0383.赎金信.md | 62 +++++++++++++++++++++++++++++++++++++++++
1 file changed, 62 insertions(+)
diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md
index 5d9e8295..8e4cbbf8 100644
--- a/problems/0383.赎金信.md
+++ b/problems/0383.赎金信.md
@@ -360,6 +360,68 @@ impl Solution {
}
}
```
+Scala:
+版本一: 使用数组作为哈希表
+```scala
+object Solution {
+ def canConstruct(ransomNote: String, magazine: String): Boolean = {
+ // 如果magazine的长度小于ransomNote的长度,必然是false
+ if (magazine.length < ransomNote.length) {
+ return false
+ }
+ // 定义一个数组,存储magazine字符出现的次数
+ val map: Array[Int] = new Array[Int](26)
+ // 遍历magazine字符串,对应的字符+=1
+ for (i <- magazine.indices) {
+ map(magazine(i) - 'a') += 1
+ }
+ // 遍历ransomNote
+ for (i <- ransomNote.indices) {
+ if (map(ransomNote(i) - 'a') > 0)
+ map(ransomNote(i) - 'a') -= 1
+ else return false
+ }
+ // 如果上面没有返回false,直接返回true,关键字return可以省略
+ true
+ }
+}
+```
+版本二: 使用HashMap
+```scala
+object Solution {
+ import scala.collection.mutable
+ def canConstruct(ransomNote: String, magazine: String): Boolean = {
+ // 如果magazine的长度小于ransomNote的长度,必然是false
+ if (magazine.length < ransomNote.length) {
+ return false
+ }
+ // 定义map,key是字符,value是字符出现的次数
+ val map = new mutable.HashMap[Char, Int]()
+ // 遍历magazine,把所有的字符都记录到map里面
+ for (i <- magazine.indices) {
+ val tmpChar = magazine(i)
+ // 如果map包含该字符,那么对应的value++,否则添加该字符
+ if (map.contains(tmpChar)) {
+ map.put(tmpChar, map.get(tmpChar).get + 1)
+ } else {
+ map.put(tmpChar, 1)
+ }
+ }
+ // 遍历ransomNote
+ for (i <- ransomNote.indices) {
+ val tmpChar = ransomNote(i)
+ // 如果map包含并且该字符的value大于0,则匹配成功,map对应的--,否则直接返回false
+ if (map.contains(tmpChar) && map.get(tmpChar).get > 0) {
+ map.put(tmpChar, map.get(tmpChar).get - 1)
+ } else {
+ return false
+ }
+ }
+ // 如果上面没有返回false,直接返回true,关键字return可以省略
+ true
+ }
+}
+```
-----------------------
From ca2711164dfd39b51f1e6d96207673ffba29d3f1 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Fri, 13 May 2022 21:11:48 +0800
Subject: [PATCH 076/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880714.?=
=?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3?=
=?UTF-8?q?=E6=97=B6=E6=9C=BA=E5=90=AB=E6=89=8B=E7=BB=AD=E8=B4=B9=E5=8A=A8?=
=?UTF-8?q?=E6=80=81=E8=A7=84=E5=88=92.md=EF=BC=89=EF=BC=9A=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
....买卖股票的最佳时机含手续费(动态规划).md | 23 +++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md
index 4ab63e79..5625604b 100644
--- a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md
+++ b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md
@@ -200,6 +200,29 @@ const maxProfit = (prices,fee) => {
}
```
+TypeScript:
+
+```typescript
+function maxProfit(prices: number[], fee: number): number {
+ /**
+ dp[i][0]:持有股票
+ dp[i][1]: 不持有
+ */
+ const length: number = prices.length;
+ if (length === 0) return 0;
+ const dp: number[][] = new Array(length).fill(0).map(_ => []);
+ dp[0][0] = -prices[0];
+ dp[0][1] = 0;
+ for (let i = 1; i < length; i++) {
+ dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
+ dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
+ }
+ return dp[length - 1][1];
+};
+```
+
+
+
-----------------------
From a53da7b4e205468bb7f870b5b46093c42923d429 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Sat, 14 May 2022 14:41:14 +0800
Subject: [PATCH 077/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200015.=E4=B8=89?=
=?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0015.三数之和.md | 43 +++++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+)
diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md
index cc184c87..1764d244 100644
--- a/problems/0015.三数之和.md
+++ b/problems/0015.三数之和.md
@@ -616,6 +616,49 @@ public class Solution
}
}
```
+Scala:
+```scala
+object Solution {
+ // 导包
+ import scala.collection.mutable.ListBuffer
+ import scala.util.control.Breaks.{break, breakable}
+ def threeSum(nums: Array[Int]): List[List[Int]] = {
+ // 定义结果集,最后需要转换为List
+ val res = ListBuffer[List[Int]]()
+ val nums_tmp = nums.sorted // 对nums进行排序
+ for (i <- nums_tmp.indices) {
+ // 如果要排的第一个数字大于0,直接返回结果
+ if (nums_tmp(i) > 0) {
+ return res.toList
+ }
+ // 如果i大于0并且和前一个数字重复,则跳过本次循环,相当于continue
+ breakable {
+ if (i > 0 && nums_tmp(i) == nums_tmp(i - 1)) {
+ break
+ } else {
+ var left = i + 1
+ var right = nums_tmp.length - 1
+ while (left < right) {
+ var sum = nums_tmp(i) + nums_tmp(left) + nums_tmp(right) // 求三数之和
+ if (sum < 0) left += 1
+ else if (sum > 0) right -= 1
+ else {
+ res += List(nums_tmp(i), nums_tmp(left), nums_tmp(right)) // 如果等于0 添加进结果集
+ // 为了避免重复,对left和right进行移动
+ while (left < right && nums_tmp(left) == nums_tmp(left + 1)) left += 1
+ while (left < right && nums_tmp(right) == nums_tmp(right - 1)) right -= 1
+ left += 1
+ right -= 1
+ }
+ }
+ }
+ }
+ }
+ // 最终返回需要转换为List,return关键字可以省略
+ res.toList
+ }
+}
+```
-----------------------
From 68eed4af5b1f43e7ac65093dd00c7497f88885cc Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Sat, 14 May 2022 15:26:29 +0800
Subject: [PATCH 078/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200018.=E5=9B=9B?=
=?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0018.四数之和.md | 45 ++++++++++++++++++++++++++++++++++++++-
1 file changed, 44 insertions(+), 1 deletion(-)
diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md
index ee70cb69..6cbd40c2 100644
--- a/problems/0018.四数之和.md
+++ b/problems/0018.四数之和.md
@@ -522,6 +522,49 @@ public class Solution
}
}
```
-
+Scala:
+```scala
+object Solution {
+ // 导包
+ import scala.collection.mutable.ListBuffer
+ import scala.util.control.Breaks.{break, breakable}
+ def fourSum(nums: Array[Int], target: Int): List[List[Int]] = {
+ val res = ListBuffer[List[Int]]()
+ val nums_tmp = nums.sorted // 先排序
+ for (i <- nums_tmp.indices) {
+ breakable {
+ if (i > 0 && nums_tmp(i) == nums_tmp(i - 1)) {
+ break // 如果该值和上次的值相同,跳过本次循环,相当于continue
+ } else {
+ for (j <- i + 1 until nums_tmp.length) {
+ breakable {
+ if (j > i + 1 && nums_tmp(j) == nums_tmp(j - 1)) {
+ break // 同上
+ } else {
+ // 双指针
+ var (left, right) = (j + 1, nums_tmp.length - 1)
+ while (left < right) {
+ var sum = nums_tmp(i) + nums_tmp(j) + nums_tmp(left) + nums_tmp(right)
+ if (sum == target) {
+ // 满足要求,直接加入到集合里面去
+ res += List(nums_tmp(i), nums_tmp(j), nums_tmp(left), nums_tmp(right))
+ while (left < right && nums_tmp(left) == nums_tmp(left + 1)) left += 1
+ while (left < right && nums_tmp(right) == nums_tmp(right - 1)) right -= 1
+ left += 1
+ right -= 1
+ } else if (sum < target) left += 1
+ else right -= 1
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ // 最终返回的res要转换为List,return关键字可以省略
+ res.toList
+ }
+}
+```
-----------------------
From e4da60add91e39177250f6808c3846c9b563612a Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Sat, 14 May 2022 15:44:42 +0800
Subject: [PATCH 079/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200344.=E5=8F=8D?=
=?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2.md=20Scala=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0344.反转字符串.md | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md
index 58bada05..e1f27bd7 100644
--- a/problems/0344.反转字符串.md
+++ b/problems/0344.反转字符串.md
@@ -266,6 +266,20 @@ public class Solution
}
}
```
-
+Scala:
+```scala
+object Solution {
+ def reverseString(s: Array[Char]): Unit = {
+ var (left, right) = (0, s.length - 1)
+ while (left < right) {
+ var tmp = s(left)
+ s(left) = s(right)
+ s(right) = tmp
+ left += 1
+ right -= 1
+ }
+ }
+}
+```
-----------------------
From f2dcdbe94757d3ef88278e4f8c80281ce7baf5c9 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Sat, 14 May 2022 16:32:23 +0800
Subject: [PATCH 080/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200541.=E5=8F=8D?=
=?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2II.md=20Scala=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0541.反转字符串II.md | 41 +++++++++++++++++++++++++++++++++++
1 file changed, 41 insertions(+)
diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md
index 8c13a390..99d6ebe0 100644
--- a/problems/0541.反转字符串II.md
+++ b/problems/0541.反转字符串II.md
@@ -347,6 +347,47 @@ public class Solution
}
}
```
+Scala:
+版本一: (正常解法)
+```scala
+object Solution {
+ def reverseStr(s: String, k: Int): String = {
+ val res = s.toCharArray // 转换为Array好处理
+ for (i <- s.indices by 2 * k) {
+ // 如果i+k大于了res的长度,则需要全部翻转
+ if (i + k > res.length) {
+ reverse(res, i, s.length - 1)
+ } else {
+ reverse(res, i, i + k - 1)
+ }
+ }
+ new String(res)
+ }
+ // 翻转字符串,从start到end
+ def reverse(s: Array[Char], start: Int, end: Int): Unit = {
+ var (left, right) = (start, end)
+ while (left < right) {
+ var tmp = s(left)
+ s(left) = s(right)
+ s(right) = tmp
+ left += 1
+ right -= 1
+ }
+ }
+}
+```
+版本二: 首先利用sliding每隔k个进行分割,随后转换为数组,再使用zipWithIndex添加每个数组的索引,紧接着利用map做变换,如果索引%2==0则说明需要翻转,否则原封不动,最后再转换为String
+```scala
+object Solution {
+ def reverseStr(s: String, k: Int): String = {
+ s.sliding(k, k)
+ .toArray
+ .zipWithIndex
+ .map(v => if (v._2 % 2 == 0) v._1.reverse else v._1)
+ .mkString
+ }
+}
+```
-----------------------
From 037bebbe90eb7bd607314d5d3d5d63e506f5aeeb Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Sat, 14 May 2022 17:04:40 +0800
Subject: [PATCH 081/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=89=91=E6=8C=87?=
=?UTF-8?q?Offer05.=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/剑指Offer05.替换空格.md | 56 +++++++++++++++++++++++++++++++-
1 file changed, 55 insertions(+), 1 deletion(-)
diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md
index 037bd427..eecd7f0c 100644
--- a/problems/剑指Offer05.替换空格.md
+++ b/problems/剑指Offer05.替换空格.md
@@ -413,8 +413,62 @@ func replaceSpace(_ s: String) -> String {
}
```
+Scala:
-
+方式一: 双指针
+```scala
+object Solution {
+ def replaceSpace(s: String): String = {
+ var count = 0
+ s.foreach(c => if (c == ' ') count += 1) // 统计空格的数量
+ val sOldSize = s.length // 旧数组字符串长度
+ val sNewSize = s.length + count * 2 // 新数组字符串长度
+ val res = new Array[Char](sNewSize) // 新数组
+ var index = sNewSize - 1 // 新数组索引
+ // 逆序遍历
+ for (i <- (0 until sOldSize).reverse) {
+ if (s(i) == ' ') {
+ res(index) = '0'
+ index -= 1
+ res(index) = '2'
+ index -= 1
+ res(index) = '%'
+ } else {
+ res(index) = s(i)
+ }
+ index -= 1
+ }
+ res.mkString
+ }
+}
+```
+方式二: 使用一个集合,遇到空格就添加%20
+```scala
+object Solution {
+ import scala.collection.mutable.ListBuffer
+ def replaceSpace(s: String): String = {
+ val res: ListBuffer[Char] = ListBuffer[Char]()
+ for (i <- s.indices) {
+ if (s(i) == ' ') {
+ res += '%'
+ res += '2'
+ res += '0'
+ }else{
+ res += s(i)
+ }
+ }
+ res.mkString
+ }
+}
+```
+方式三: 使用map
+```scala
+object Solution {
+ def replaceSpace(s: String): String = {
+ s.map(c => if(c == ' ') "%20" else c).mkString
+ }
+}
+```
-----------------------
From 1c369bb83631f4449af7e646bc26bc86aacc5442 Mon Sep 17 00:00:00 2001
From: 3Xpl0it3r
Date: Sat, 14 May 2022 23:24:57 +0800
Subject: [PATCH 082/162] 102 in rust
---
problems/0102.二叉树的层序遍历.md | 59 +++++++++++++++++++++++++++++++
1 file changed, 59 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index ab8f2e57..13267819 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -299,6 +299,36 @@ func levelOrder(_ root: TreeNode?) -> [[Int]] {
}
```
+Rust:
+
+```rust
+pub fn level_order(root: Option>>) -> Vec> {
+ let mut ans = Vec::new();
+ let mut stack = Vec::new();
+ if root.is_none(){
+ return ans;
+ }
+ stack.push(root.unwrap());
+ while stack.is_empty()!= true{
+ let num = stack.len();
+ let mut level = Vec::new();
+ for _i in 0..num{
+ let tmp = stack.remove(0);
+ level.push(tmp.borrow_mut().val);
+ if tmp.borrow_mut().left.is_some(){
+ stack.push(tmp.borrow_mut().left.take().unwrap());
+ }
+ if tmp.borrow_mut().right.is_some(){
+ stack.push(tmp.borrow_mut().right.take().unwrap());
+ }
+ }
+ ans.push(level);
+ }
+ ans
+}
+```
+
+
**此时我们就掌握了二叉树的层序遍历了,那么如下九道力扣上的题目,只需要修改模板的两三行代码(不能再多了),便可打倒!**
@@ -528,6 +558,35 @@ func levelOrderBottom(_ root: TreeNode?) -> [[Int]] {
}
```
+Rust:
+
+```rust
+pub fn level_order(root: Option>>) -> Vec> {
+ let mut ans = Vec::new();
+ let mut stack = Vec::new();
+ if root.is_none(){
+ return ans;
+ }
+ stack.push(root.unwrap());
+ while stack.is_empty()!= true{
+ let num = stack.len();
+ let mut level = Vec::new();
+ for _i in 0..num{
+ let tmp = stack.remove(0);
+ level.push(tmp.borrow_mut().val);
+ if tmp.borrow_mut().left.is_some(){
+ stack.push(tmp.borrow_mut().left.take().unwrap());
+ }
+ if tmp.borrow_mut().right.is_some(){
+ stack.push(tmp.borrow_mut().right.take().unwrap());
+ }
+ }
+ ans.push(level);
+ }
+ ans
+}
+```
+
# 199.二叉树的右视图
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/)
From ab4d42cf0c41ce9089838dee087e961aac1b6357 Mon Sep 17 00:00:00 2001
From: n4feng
Date: Sat, 14 May 2022 12:52:11 -0400
Subject: [PATCH 083/162] =?UTF-8?q?Update=200739.=E6=AF=8F=E6=97=A5?=
=?UTF-8?q?=E6=B8=A9=E5=BA=A6.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
少了一个关键词“高”
---
problems/0739.每日温度.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md
index 5f53e412..367e521a 100644
--- a/problems/0739.每日温度.md
+++ b/problems/0739.每日温度.md
@@ -34,7 +34,7 @@
那么单调栈的原理是什么呢?为什么时间复杂度是O(n)就可以找到每一个元素的右边第一个比它大的元素位置呢?
-单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素的元素,优点是只需要遍历一次。
+单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素高的元素,优点是只需要遍历一次。
在使用单调栈的时候首先要明确如下几点:
From 78b367e5c5ee493a96cfe4ebcb440059909db285 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Sun, 15 May 2022 12:57:39 +0800
Subject: [PATCH 084/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200151.=E7=BF=BB?=
=?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95?=
=?UTF-8?q?=E8=AF=8D.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0151.翻转字符串里的单词.md | 56 +++++++++++++++++++++++++++++
1 file changed, 56 insertions(+)
diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md
index d03de421..0e25fc4d 100644
--- a/problems/0151.翻转字符串里的单词.md
+++ b/problems/0151.翻转字符串里的单词.md
@@ -758,7 +758,63 @@ func reverseWord(_ s: inout [Character]) {
}
```
+Scala:
+```scala
+object Solution {
+ def reverseWords(s: String): String = {
+ var sb = removeSpace(s) // 移除多余的空格
+ reverseString(sb, 0, sb.length - 1) // 翻转字符串
+ reverseEachWord(sb)
+ sb.mkString
+ }
+
+ // 移除多余的空格
+ def removeSpace(s: String): Array[Char] = {
+ var start = 0
+ var end = s.length - 1
+ // 移除字符串前面的空格
+ while (start < s.length && s(start) == ' ') start += 1
+ // 移除字符串后面的空格
+ while (end >= 0 && s(end) == ' ') end -= 1
+ var sb = "" // String
+ // 当start小于等于end的时候,执行添加操作
+ while (start <= end) {
+ var c = s(start)
+ // 当前字符不等于空,sb的最后一个字符不等于空的时候添加到sb
+ if (c != ' ' || sb(sb.length - 1) != ' ') {
+ sb ++= c.toString
+ }
+ start += 1 // 指针向右移动
+ }
+ sb.toArray
+ }
+
+ // 翻转字符串
+ def reverseString(s: Array[Char], start: Int, end: Int): Unit = {
+ var (left, right) = (start, end)
+ while (left < right) {
+ var tmp = s(left)
+ s(left) = s(right)
+ s(right) = tmp
+ left += 1
+ right -= 1
+ }
+ }
+
+ // 翻转每个单词
+ def reverseEachWord(s: Array[Char]): Unit = {
+ var i = 0
+ while (i < s.length) {
+ var j = i + 1
+ // 向后迭代寻找每个单词的坐标
+ while (j < s.length && s(j) != ' ') j += 1
+ reverseString(s, i, j - 1) // 翻转每个单词
+ i = j + 1 // i往后更新
+ }
+ }
+}
+```
From c7d356f8559fd2c46eb4e9e2889fdbe0bdaafed1 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Sun, 15 May 2022 12:59:38 +0800
Subject: [PATCH 085/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=89=91=E6=8C=87?=
=?UTF-8?q?Offer58-II.=E5=B7=A6=E6=97=8B=E8=BD=AC=E5=AD=97=E7=AC=A6?=
=?UTF-8?q?=E4=B8=B2.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/剑指Offer58-II.左旋转字符串.md | 27 +++++++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md
index fec83e1d..581ac1c7 100644
--- a/problems/剑指Offer58-II.左旋转字符串.md
+++ b/problems/剑指Offer58-II.左旋转字符串.md
@@ -290,7 +290,34 @@ func reverseString(_ s: inout [Character], startIndex: Int, endIndex: Int) {
}
```
+Scala:
+```scala
+object Solution {
+ def reverseLeftWords(s: String, n: Int): String = {
+ var str = s.toCharArray // 转换为Array
+ // abcdefg => ba cdefg
+ reverseString(str, 0, n - 1)
+ // ba cdefg => ba gfedc
+ reverseString(str, n, str.length - 1)
+ // ba gfedc => cdefgab
+ reverseString(str, 0, str.length - 1)
+ // 最终返回,return关键字可以省略
+ new String(str)
+ }
+ // 翻转字符串
+ def reverseString(s: Array[Char], start: Int, end: Int): Unit = {
+ var (left, right) = (start, end)
+ while (left < right) {
+ var tmp = s(left)
+ s(left) = s(right)
+ s(right) = tmp
+ left += 1
+ right -= 1
+ }
+ }
+}
+```
From a5db99363b1bca72345036228776a0320242c8c4 Mon Sep 17 00:00:00 2001
From: SevenMonths
Date: Sun, 15 May 2022 15:35:08 +0800
Subject: [PATCH 086/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880035.?=
=?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=8F=92=E5=85=A5=E4=BD=8D=E7=BD=AE.md?=
=?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0PHP=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0035.搜索插入位置.md | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md
index 9a770703..8a8f9706 100644
--- a/problems/0035.搜索插入位置.md
+++ b/problems/0035.搜索插入位置.md
@@ -318,6 +318,31 @@ func searchInsert(_ nums: [Int], _ target: Int) -> Int {
```
+### PHP
+
+```php
+// 二分法(1):[左闭右闭]
+function searchInsert($nums, $target)
+{
+ $n = count($nums);
+ $l = 0;
+ $r = $n - 1;
+ while ($l <= $r) {
+ $mid = floor(($l + $r) / 2);
+ if ($nums[$mid] > $target) {
+ // 下次搜索在左区间:[$l,$mid-1]
+ $r = $mid - 1;
+ } else if ($nums[$mid] < $target) {
+ // 下次搜索在右区间:[$mid+1,$r]
+ $l = $mid + 1;
+ } else {
+ // 命中返回
+ return $mid;
+ }
+ }
+ return $r + 1;
+}
+```
-----------------------
From f1061d0f8962fe8e4a4c0691d8401ee5fe505f99 Mon Sep 17 00:00:00 2001
From: GitHubQAQ <31883473+GitHubQAQ@users.noreply.github.com>
Date: Sun, 15 May 2022 19:12:13 +0800
Subject: [PATCH 087/162] =?UTF-8?q?Update=200056.=E5=90=88=E5=B9=B6?=
=?UTF-8?q?=E5=8C=BA=E9=97=B4.md=20=20-=20-=E8=A7=84=E8=8C=83C++=E4=BB=A3?=
=?UTF-8?q?=E7=A0=81=E4=B8=AD=E7=9A=84lambda=E8=A1=A8=E8=BF=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0056.合并区间.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md
index b44d602c..52a98d70 100644
--- a/problems/0056.合并区间.md
+++ b/problems/0056.合并区间.md
@@ -96,7 +96,7 @@ public:
vector> merge(vector>& intervals) {
vector> result;
if (intervals.size() == 0) return result;
- // 排序的参数使用了lamda表达式
+ // 排序的参数使用了lambda表达式
sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b){return a[0] < b[0];});
result.push_back(intervals[0]);
From 224b3d293b6b2c9465e00b2127cf1d75f44775df Mon Sep 17 00:00:00 2001
From: wangning
Date: Sun, 15 May 2022 20:15:11 +0800
Subject: [PATCH 088/162] =?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=9A0404?=
=?UTF-8?q?=E5=B7=A6=E5=8F=B6=E5=AD=90=E4=B9=8B=E5=92=8Cjavascript?=
=?UTF-8?q?=E7=89=88=E6=9C=AC=E8=B0=83=E7=94=A8=E6=96=B9=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0404.左叶子之和.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md
index d7fd629e..4ef68d3b 100644
--- a/problems/0404.左叶子之和.md
+++ b/problems/0404.左叶子之和.md
@@ -336,8 +336,8 @@ var sumOfLeftLeaves = function(root) {
if(node===null){
return 0;
}
- let leftValue = sumOfLeftLeaves(node.left);
- let rightValue = sumOfLeftLeaves(node.right);
+ let leftValue = nodesSum(node.left);
+ let rightValue = nodesSum(node.right);
// 3. 单层递归逻辑
let midValue = 0;
if(node.left&&node.left.left===null&&node.left.right===null){
From 14afd23b9ea5e491a60d91f07c0b8211f4f9ae00 Mon Sep 17 00:00:00 2001
From: HanMengnan <1448189829@qq.com>
Date: Mon, 16 May 2022 10:46:43 +0800
Subject: [PATCH 089/162] =?UTF-8?q?=E6=9B=B4=E6=96=B00516.=E6=9C=80?=
=?UTF-8?q?=E9=95=BF=E5=9B=9E=E6=96=87=E5=AD=90=E5=BA=8F=E5=88=97=E7=9A=84?=
=?UTF-8?q?Go=E5=AE=9E=E7=8E=B0=E6=8F=90=E4=BE=9B=E4=BA=86=E4=B8=80?=
=?UTF-8?q?=E7=A7=8D=E6=9B=B4=E4=BC=98=E7=9A=84=E6=96=B9=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0516.最长回文子序列.md | 39 ++++++++++++++++-----------------
1 file changed, 19 insertions(+), 20 deletions(-)
diff --git a/problems/0516.最长回文子序列.md b/problems/0516.最长回文子序列.md
index 69536cef..63120b14 100644
--- a/problems/0516.最长回文子序列.md
+++ b/problems/0516.最长回文子序列.md
@@ -186,29 +186,28 @@ class Solution:
Go:
```Go
func longestPalindromeSubseq(s string) int {
- lenth:=len(s)
- dp:=make([][]int,lenth)
- for i:=0;i b {
+ return a
+ }
+ return b
+ }
+ dp := make([][]int, size)
+ for i := 0; i < size; i++ {
+ dp[i] = make([]int, size)
+ dp[i][i] = 1
+ }
+ for i := size - 1; i >= 0; i-- {
+ for j := i + 1; j < size; j++ {
+ if s[i] == s[j] {
+ dp[i][j] = dp[i+1][j-1] + 2
+ } else {
+ dp[i][j] = max(dp[i][j-1], dp[i+1][j])
}
}
}
- for i:=lenth-1;i>=0;i--{
- for j:=i+1;j
Date: Mon, 16 May 2022 14:51:05 +0900
Subject: [PATCH 090/162] chore: Add new solution to LeetCode 203
Without using pre Node
---
problems/0203.移除链表元素.md | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md
index c34831b7..9cedfe93 100644
--- a/problems/0203.移除链表元素.md
+++ b/problems/0203.移除链表元素.md
@@ -234,6 +234,27 @@ public ListNode removeElements(ListNode head, int val) {
}
return head;
}
+/**
+ * 不添加虚拟节点and pre Node方式
+ * 时间复杂度 O(n)
+ * 空间复杂度 O(1)
+ * @param head
+ * @param val
+ * @return
+ */
+public ListNode removeElements(ListNode head, int val) {
+ while(head!=null && head.val==val){
+ head = head.next;
+ }
+ ListNode curr = head;
+ while(curr!=null){
+ while(curr.next!=null && curr.next.val == val){
+ curr.next = curr.next.next;
+ }
+ curr = curr.next;
+ }
+ return head;
+}
```
Python:
From 08147d132c4611e190d03a47bc870294d3cc1292 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Mon, 16 May 2022 14:28:02 +0800
Subject: [PATCH 091/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200232.=E7=94=A8?=
=?UTF-8?q?=E6=A0=88=E5=AE=9E=E7=8E=B0=E9=98=9F=E5=88=97.md=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0232.用栈实现队列.md | 39 +++++++++++++++++++++++++++++++++++
1 file changed, 39 insertions(+)
diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md
index 1a56d9f3..d9ba8e26 100644
--- a/problems/0232.用栈实现队列.md
+++ b/problems/0232.用栈实现队列.md
@@ -495,6 +495,45 @@ void myQueueFree(MyQueue* obj) {
obj->stackOutTop = 0;
}
```
+Scala:
+```scala
+class MyQueue() {
+ import scala.collection.mutable
+ val stackIn = mutable.Stack[Int]() // 负责出栈
+ val stackOut = mutable.Stack[Int]() // 负责入栈
+ // 添加元素
+ def push(x: Int) {
+ stackIn.push(x)
+ }
+
+ // 复用代码,如果stackOut为空就把stackIn的所有元素都压入StackOut
+ def dumpStackIn(): Unit = {
+ if (!stackOut.isEmpty) return
+ while (!stackIn.isEmpty) {
+ stackOut.push(stackIn.pop())
+ }
+ }
+
+ // 弹出元素
+ def pop(): Int = {
+ dumpStackIn()
+ stackOut.pop()
+ }
+
+ // 获取队头
+ def peek(): Int = {
+ dumpStackIn()
+ val res: Int = stackOut.pop()
+ stackOut.push(res)
+ res
+ }
+
+ // 判断是否为空
+ def empty(): Boolean = {
+ stackIn.isEmpty && stackOut.isEmpty
+ }
+}
+```
-----------------------
From f4d98a744ee9c14ed88d07be559aa310508d89f9 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Mon, 16 May 2022 14:56:10 +0800
Subject: [PATCH 092/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200225.=E7=94=A8?=
=?UTF-8?q?=E9=98=9F=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88.md=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0225.用队列实现栈.md | 83 +++++++++++++++++++++++++++++++++++
1 file changed, 83 insertions(+)
diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md
index 3457c4b3..3c134870 100644
--- a/problems/0225.用队列实现栈.md
+++ b/problems/0225.用队列实现栈.md
@@ -815,6 +815,89 @@ class MyStack {
}
}
```
+Scala:
+使用两个队列模拟栈:
+```scala
+import scala.collection.mutable
+
+class MyStack() {
+
+ val queue1 = new mutable.Queue[Int]()
+ val queue2 = new mutable.Queue[Int]()
+
+ def push(x: Int) {
+ queue1.enqueue(x)
+ }
+
+ def pop(): Int = {
+ var size = queue1.size
+ // 将queue1中的每个元素都移动到queue2
+ for (i <- 0 until size - 1) {
+ queue2.enqueue(queue1.dequeue())
+ }
+ var res = queue1.dequeue()
+ // 再将queue2中的每个元素都移动到queue1
+ while (!queue2.isEmpty) {
+ queue1.enqueue(queue2.dequeue())
+ }
+ res
+ }
+
+ def top(): Int = {
+ var size = queue1.size
+ for (i <- 0 until size - 1) {
+ queue2.enqueue(queue1.dequeue())
+ }
+ var res = queue1.dequeue()
+ while (!queue2.isEmpty) {
+ queue1.enqueue(queue2.dequeue())
+ }
+ // 最终还需要把res送进queue1
+ queue1.enqueue(res)
+ res
+ }
+
+ def empty(): Boolean = {
+ queue1.isEmpty
+ }
+}
+```
+使用一个队列模拟:
+```scala
+import scala.collection.mutable
+
+class MyStack() {
+
+ val queue = new mutable.Queue[Int]()
+
+ def push(x: Int) {
+ queue.enqueue(x)
+ }
+
+ def pop(): Int = {
+ var size = queue.size
+ for (i <- 0 until size - 1) {
+ queue.enqueue(queue.head) // 把头添到队列最后
+ queue.dequeue() // 再出队
+ }
+ queue.dequeue()
+ }
+
+ def top(): Int = {
+ var size = queue.size
+ var res = 0
+ for (i <- 0 until size) {
+ queue.enqueue(queue.head) // 把头添到队列最后
+ res = queue.dequeue() // 再出队
+ }
+ res
+ }
+
+ def empty(): Boolean = {
+ queue.isEmpty
+ }
+}
+```
-----------------------
From 8df1b4b237552c189fa1a5788442c422c9296d07 Mon Sep 17 00:00:00 2001
From: madeai
Date: Mon, 16 May 2022 16:38:53 +0800
Subject: [PATCH 093/162] =?UTF-8?q?Update=200739.=E6=AF=8F=E6=97=A5?=
=?UTF-8?q?=E6=B8=A9=E5=BA=A6.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0739.每日温度.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md
index 5f53e412..2305d135 100644
--- a/problems/0739.每日温度.md
+++ b/problems/0739.每日温度.md
@@ -192,7 +192,7 @@ class Solution {
否则的话,可以直接入栈。
注意,单调栈里 加入的元素是 下标。
*/
- Stackstack=new Stack<>();
+ Deque stack=new LinkedList<>();
stack.push(0);
for(int i=1;istack=new Stack<>();
+ Deque stack=new LinkedList<>();
for(int i=0;itemperatures[stack.peek()]){
From 61f5d920d05ea01858272bc04f8bcea0a89d6991 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Mon, 16 May 2022 17:07:23 +0800
Subject: [PATCH 094/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200020.=E6=9C=89?=
=?UTF-8?q?=E6=95=88=E7=9A=84=E6=8B=AC=E5=8F=B7.md=20Scala=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0020.有效的括号.md | 23 ++++++++++++++++++++++-
1 file changed, 22 insertions(+), 1 deletion(-)
diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md
index 7bb7f746..a0df0d07 100644
--- a/problems/0020.有效的括号.md
+++ b/problems/0020.有效的括号.md
@@ -400,6 +400,27 @@ bool isValid(char * s){
return !stackTop;
}
```
-
+Scala:
+```scala
+object Solution {
+ import scala.collection.mutable
+ def isValid(s: String): Boolean = {
+ if(s.length % 2 != 0) return false // 如果字符串长度是奇数直接返回false
+ val stack = mutable.Stack[Char]()
+ // 循环遍历字符串
+ for (i <- s.indices) {
+ val c = s(i)
+ if (c == '(' || c == '[' || c == '{') stack.push(c)
+ else if(stack.isEmpty) return false // 如果没有(、[、{则直接返回false
+ // 以下三种情况,不满足则直接返回false
+ else if(c==')' && stack.pop() != '(') return false
+ else if(c==']' && stack.pop() != '[') return false
+ else if(c=='}' && stack.pop() != '{') return false
+ }
+ // 如果为空则正确匹配,否则还有余孽就不匹配
+ stack.isEmpty
+ }
+}
+```
-----------------------
From 98bdccbe16bbb6c8c66e027d901f4fbd3baafffe Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Mon, 16 May 2022 17:24:47 +0800
Subject: [PATCH 095/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=201047.=E5=88=A0?=
=?UTF-8?q?=E9=99=A4=E5=AD=97=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=9A=84=E6=89=80?=
=?UTF-8?q?=E6=9C=89=E7=9B=B8=E9=82=BB=E9=87=8D=E5=A4=8D=E9=A1=B9.md=20Sca?=
=?UTF-8?q?la=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/1047.删除字符串中的所有相邻重复项.md | 23 ++++++++++++++++++-
1 file changed, 22 insertions(+), 1 deletion(-)
diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md
index 638c8f4e..a92a3911 100644
--- a/problems/1047.删除字符串中的所有相邻重复项.md
+++ b/problems/1047.删除字符串中的所有相邻重复项.md
@@ -374,6 +374,27 @@ func removeDuplicates(_ s: String) -> String {
return String(stack)
}
```
-
+Scala:
+```scala
+object Solution {
+ import scala.collection.mutable
+ def removeDuplicates(s: String): String = {
+ var stack = mutable.Stack[Int]()
+ var str = "" // 保存最终结果
+ for (i <- s.indices) {
+ var tmp = s(i)
+ // 如果栈非空并且栈顶元素等于当前字符,那么删掉栈顶和字符串最后一个元素
+ if (!stack.isEmpty && tmp == stack.head) {
+ str = str.take(str.length - 1)
+ stack.pop()
+ } else {
+ stack.push(tmp)
+ str += tmp
+ }
+ }
+ str
+ }
+}
+```
-----------------------
From 8c394c9f8588a1e94250dc93bede24b7380996f8 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Tue, 17 May 2022 17:08:11 +0800
Subject: [PATCH 096/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200150.=E9=80=86?=
=?UTF-8?q?=E6=B3=A2=E5=85=B0=E8=A1=A8=E8=BE=BE=E5=BC=8F=E6=B1=82=E5=80=BC?=
=?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0150.逆波兰表达式求值.md | 29 ++++++++++++++++++++++++++++-
1 file changed, 28 insertions(+), 1 deletion(-)
diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md
index fd3d69aa..47da06f6 100644
--- a/problems/0150.逆波兰表达式求值.md
+++ b/problems/0150.逆波兰表达式求值.md
@@ -325,6 +325,33 @@ func evalRPN(_ tokens: [String]) -> Int {
return stack.last!
}
```
-
+Scala:
+```scala
+object Solution {
+ import scala.collection.mutable
+ def evalRPN(tokens: Array[String]): Int = {
+ val stack = mutable.Stack[Int]() // 定义栈
+ // 抽取运算操作,需要传递x,y,和一个函数
+ def operator(x: Int, y: Int, f: (Int, Int) => Int): Int = f(x, y)
+ for (token <- tokens) {
+ // 模式匹配,匹配不同的操作符做什么样的运算
+ token match {
+ // 最后一个参数 _+_,代表x+y,遵循Scala的函数至简原则,以下运算同理
+ case "+" => stack.push(operator(stack.pop(), stack.pop(), _ + _))
+ case "-" => stack.push(operator(stack.pop(), stack.pop(), -_ + _))
+ case "*" => stack.push(operator(stack.pop(), stack.pop(), _ * _))
+ case "/" => {
+ var pop1 = stack.pop()
+ var pop2 = stack.pop()
+ stack.push(operator(pop2, pop1, _ / _))
+ }
+ case _ => stack.push(token.toInt) // 不是运算符就入栈
+ }
+ }
+ // 最后返回栈顶,不需要加return关键字
+ stack.pop()
+ }
+}
+```
-----------------------
From 349383321ff1ed393effb9ebaad075a7736cf98e Mon Sep 17 00:00:00 2001
From: SevenMonths
Date: Tue, 17 May 2022 17:45:40 +0800
Subject: [PATCH 097/162] =?UTF-8?q?=E5=A2=9E=E5=8A=A0KMP=20php=E7=89=88?=
=?UTF-8?q?=E6=9C=AC=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0028.实现strStr.md | 75 +++++++++++++++++++++++++++++++++++++
1 file changed, 75 insertions(+)
diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md
index d67e5f70..1cdd5292 100644
--- a/problems/0028.实现strStr.md
+++ b/problems/0028.实现strStr.md
@@ -1166,5 +1166,80 @@ func strStr(_ haystack: String, _ needle: String) -> Int {
```
+PHP:
+
+> 前缀表统一减一
+```php
+function strStr($haystack, $needle) {
+ if (strlen($needle) == 0) return 0;
+ $next= [];
+ $this->getNext($next,$needle);
+
+ $j = -1;
+ for ($i = 0;$i < strlen($haystack); $i++) { // 注意i就从0开始
+ while($j >= 0 && $haystack[$i] != $needle[$j + 1]) {
+ $j = $next[$j];
+ }
+ if ($haystack[$i] == $needle[$j + 1]) {
+ $j++;
+ }
+ if ($j == (strlen($needle) - 1) ) {
+ return ($i - strlen($needle) + 1);
+ }
+ }
+ return -1;
+}
+
+function getNext(&$next, $s){
+ $j = -1;
+ $next[0] = $j;
+ for($i = 1; $i < strlen($s); $i++) { // 注意i从1开始
+ while ($j >= 0 && $s[$i] != $s[$j + 1]) {
+ $j = $next[$j];
+ }
+ if ($s[$i] == $s[$j + 1]) {
+ $j++;
+ }
+ $next[$i] = $j;
+ }
+}
+```
+
+> 前缀表统一不减一
+```php
+function strStr($haystack, $needle) {
+ if (strlen($needle) == 0) return 0;
+ $next= [];
+ $this->getNext($next,$needle);
+
+ $j = 0;
+ for ($i = 0;$i < strlen($haystack); $i++) { // 注意i就从0开始
+ while($j > 0 && $haystack[$i] != $needle[$j]) {
+ $j = $next[$j-1];
+ }
+ if ($haystack[$i] == $needle[$j]) {
+ $j++;
+ }
+ if ($j == strlen($needle)) {
+ return ($i - strlen($needle) + 1);
+ }
+ }
+ return -1;
+}
+
+function getNext(&$next, $s){
+ $j = 0;
+ $next[0] = $j;
+ for($i = 1; $i < strlen($s); $i++) { // 注意i从1开始
+ while ($j > 0 && $s[$i] != $s[$j]) {
+ $j = $next[$j-1];
+ }
+ if ($s[$i] == $s[$j]) {
+ $j++;
+ }
+ $next[$i] = $j;
+ }
+}
+```
-----------------------
From 748a728420be62c835866e7027171462ef90f888 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Tue, 17 May 2022 18:41:52 +0800
Subject: [PATCH 098/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200239.=E6=BB=91?=
=?UTF-8?q?=E5=8A=A8=E7=AA=97=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC.md=20Sca?=
=?UTF-8?q?la=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0239.滑动窗口最大值.md | 47 +++++++++++++++++++++++++++++++++
1 file changed, 47 insertions(+)
diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md
index f269450f..eb32fdd2 100644
--- a/problems/0239.滑动窗口最大值.md
+++ b/problems/0239.滑动窗口最大值.md
@@ -630,6 +630,53 @@ func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
return result
}
```
+Scala:
+```scala
+import scala.collection.mutable.ArrayBuffer
+object Solution {
+ def maxSlidingWindow(nums: Array[Int], k: Int): Array[Int] = {
+ var len = nums.length - k + 1 // 滑动窗口长度
+ var res: Array[Int] = new Array[Int](len) // 声明存储结果的数组
+ var index = 0 // 结果数组指针
+ val queue: MyQueue = new MyQueue // 自定义队列
+ // 将前k个添加到queue
+ for (i <- 0 until k) {
+ queue.add(nums(i))
+ }
+ res(index) = queue.peek // 第一个滑动窗口的最大值
+ index += 1
+ for (i <- k until nums.length) {
+ queue.poll(nums(i - k)) // 首先移除第i-k个元素
+ queue.add(nums(i)) // 添加当前数字到队列
+ res(index) = queue.peek() // 赋值
+ index+=1
+ }
+ // 最终返回res,return关键字可以省略
+ res
+ }
+}
+
+class MyQueue {
+ var queue = ArrayBuffer[Int]()
+
+ // 移除元素,如果传递进来的跟队头相等,那么移除
+ def poll(value: Int): Unit = {
+ if (!queue.isEmpty && queue.head == value) {
+ queue.remove(0)
+ }
+ }
+
+ // 添加元素,当队尾大于当前元素就删除
+ def add(value: Int): Unit = {
+ while (!queue.isEmpty && value > queue.last) {
+ queue.remove(queue.length - 1)
+ }
+ queue.append(value)
+ }
+
+ def peek(): Int = queue.head
+}
+```
-----------------------
From 47c4cc102123b1b43f09b7b766fdd2f1e1b979a9 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Tue, 17 May 2022 19:52:32 +0800
Subject: [PATCH 099/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200347.=E5=89=8DK?=
=?UTF-8?q?=E4=B8=AA=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0.md=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0347.前K个高频元素.md | 42 ++++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md
index 1d6a358b..20932b28 100644
--- a/problems/0347.前K个高频元素.md
+++ b/problems/0347.前K个高频元素.md
@@ -374,7 +374,49 @@ function topKFrequent(nums: number[], k: number): number[] {
};
```
+Scala:
+解法一: 优先级队列
+```scala
+object Solution {
+ import scala.collection.mutable
+ def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
+ val map = mutable.HashMap[Int, Int]()
+ // 将所有元素都放入Map
+ for (num <- nums) {
+ map.put(num, map.getOrElse(num, 0) + 1)
+ }
+ // 声明一个优先级队列,在函数柯里化那块需要指明排序方式
+ var queue = mutable.PriorityQueue[(Int, Int)]()(Ordering.fromLessThan((x, y) => x._2 > y._2))
+ // 将map里面的元素送入优先级队列
+ for (elem <- map) {
+ queue.enqueue(elem)
+ if(queue.size > k){
+ queue.dequeue // 如果队列元素大于k个,出队
+ }
+ }
+ // 最终只需要key的Array形式就可以了,return关键字可以省略
+ queue.map(_._1).toArray
+ }
+}
+```
+解法二: 相当于一个wordCount程序
+```scala
+object Solution {
+ def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
+ // 首先将数据变为(x,1),然后按照x分组,再使用map进行转换(x,sum),变换为Array
+ // 再使用sort针对sum进行排序,最后take前k个,再把数据变为x,y,z这种格式
+ nums.map((_, 1)).groupBy(_._1)
+ .map {
+ case (x, arr) => (x, arr.map(_._2).sum)
+ }
+ .toArray
+ .sortWith(_._2 > _._2)
+ .take(k)
+ .map(_._1)
+ }
+}
+```
-----------------------
From 6457d2d99775e9eddc1ab8386cdd5ca2d916b4b7 Mon Sep 17 00:00:00 2001
From: whusky <31883473+GitHubQAQ@users.noreply.github.com>
Date: Tue, 17 May 2022 21:22:17 +0800
Subject: [PATCH 100/162] =?UTF-8?q?Update=200063.=E4=B8=8D=E5=90=8C?=
=?UTF-8?q?=E8=B7=AF=E5=BE=84II.md=20=20=E6=B7=BB=E5=8A=A0=E9=A2=84?=
=?UTF-8?q?=E5=88=A4=E6=96=AD=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
1. 优化代码高亮格式
2. 对于C++的第一种解法添加预判断代码
---
problems/0063.不同路径II.md | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md
index a40cceda..0e51e0fe 100644
--- a/problems/0063.不同路径II.md
+++ b/problems/0063.不同路径II.md
@@ -66,7 +66,7 @@ dp[i][j] :表示从(0 ,0)出发,到(i, j) 有dp[i][j]条不同的路
所以代码为:
-```
+```cpp
if (obstacleGrid[i][j] == 0) { // 当(i, j)没有障碍的时候,再推导dp[i][j]
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
@@ -76,7 +76,7 @@ if (obstacleGrid[i][j] == 0) { // 当(i, j)没有障碍的时候,再推导dp[i
在[62.不同路径](https://programmercarl.com/0062.不同路径.html)不同路径中我们给出如下的初始化:
-```
+```cpp
vector> dp(m, vector(n, 0)); // 初始值为0
for (int i = 0; i < m; i++) dp[i][0] = 1;
for (int j = 0; j < n; j++) dp[0][j] = 1;
@@ -138,6 +138,8 @@ public:
int uniquePathsWithObstacles(vector>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
+ if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) //如果在起点或终点出现了障碍,直接返回0
+ return 0;
vector> dp(m, vector(n, 0));
for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) dp[i][0] = 1;
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) dp[0][j] = 1;
From 83c2fd2454bbbbeda82725d2c38a2b577d7434c6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?=
Date: Wed, 18 May 2022 09:27:56 +0800
Subject: [PATCH 101/162] Update README.md
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 3d44ca69..01cab0b0 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@
-# LeetCode 刷题攻略1111
+# LeetCode 刷题攻略
## 刷题攻略的背景
From 552e24b171bae840f32ab865ae4518c8674492e3 Mon Sep 17 00:00:00 2001
From: molonlu
Date: Wed, 18 May 2022 11:49:55 +0800
Subject: [PATCH 102/162] =?UTF-8?q?Update=200226.=E7=BF=BB=E8=BD=AC?=
=?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
通过tmp显示交换的方式改为golang风格的交换
---
problems/0226.翻转二叉树.md | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md
index a3ebe24d..af5b8043 100644
--- a/problems/0226.翻转二叉树.md
+++ b/problems/0226.翻转二叉树.md
@@ -368,9 +368,7 @@ func invertTree(root *TreeNode) *TreeNode {
if root ==nil{
return nil
}
- temp:=root.Left
- root.Left=root.Right
- root.Right=temp
+ root.Left,root.Right=root.Right,root.Left//交换
invertTree(root.Left)
invertTree(root.Right)
From f389dcd987a7f9b381f146de9846fc4abfdb92ae Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 18 May 2022 16:23:50 +0800
Subject: [PATCH 103/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=8F=89?=
=?UTF-8?q?=E6=A0=91=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/二叉树理论基础.md | 9 ++++++++-
1 file changed, 8 insertions(+), 1 deletion(-)
diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md
index 9c151e32..9e10ac20 100644
--- a/problems/二叉树理论基础.md
+++ b/problems/二叉树理论基础.md
@@ -258,6 +258,13 @@ class TreeNode {
}
}
```
-
+Scala:
+```scala
+class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
+ var value: Int = _value
+ var left: TreeNode = _left
+ var right: TreeNode = _right
+}
+```
-----------------------
From b2be41e4bcd2c1ef6bc4951519e5134209b55689 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 18 May 2022 16:54:15 +0800
Subject: [PATCH 104/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=8F=89?=
=?UTF-8?q?=E6=A0=91=E7=9A=84=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86.md=20Sca?=
=?UTF-8?q?la=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/二叉树的递归遍历.md | 51 ++++++++++++++++++++++++++++++++++++
1 file changed, 51 insertions(+)
diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md
index 186c39d3..29c0cfda 100644
--- a/problems/二叉树的递归遍历.md
+++ b/problems/二叉树的递归遍历.md
@@ -470,5 +470,56 @@ func postorder(_ root: TreeNode?, res: inout [Int]) {
res.append(root!.val)
}
```
+Scala: 前序遍历:(144.二叉树的前序遍历)
+```scala
+object Solution {
+ import scala.collection.mutable.ListBuffer
+ def preorderTraversal(root: TreeNode): List[Int] = {
+ val res = ListBuffer[Int]()
+ def traversal(curNode: TreeNode): Unit = {
+ if(curNode == null) return
+ res.append(curNode.value)
+ traversal(curNode.left)
+ traversal(curNode.right)
+ }
+ traversal(root)
+ res.toList
+ }
+}
+```
+中序遍历:(94. 二叉树的中序遍历)
+```scala
+object Solution {
+ import scala.collection.mutable.ListBuffer
+ def inorderTraversal(root: TreeNode): List[Int] = {
+ val res = ListBuffer[Int]()
+ def traversal(curNode: TreeNode): Unit = {
+ if(curNode == null) return
+ traversal(curNode.left)
+ res.append(curNode.value)
+ traversal(curNode.right)
+ }
+ traversal(root)
+ res.toList
+ }
+}
+```
+后序遍历:(145. 二叉树的后序遍历)
+```scala
+object Solution {
+ import scala.collection.mutable.ListBuffer
+ def postorderTraversal(root: TreeNode): List[Int] = {
+ val res = ListBuffer[Int]()
+ def traversal(curNode: TreeNode): Unit = {
+ if (curNode == null) return
+ traversal(curNode.left)
+ traversal(curNode.right)
+ res.append(curNode.value)
+ }
+ traversal(root)
+ res.toList
+ }
+}
+```
-----------------------
From d6d227c4affd046a47429454aa241bae12c7def2 Mon Sep 17 00:00:00 2001
From: areslk <543430610@qq.com>
Date: Wed, 18 May 2022 17:07:40 +0800
Subject: [PATCH 105/162] =?UTF-8?q?Update=200110.=E5=B9=B3=E8=A1=A1?=
=?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
修改注释
---
problems/0110.平衡二叉树.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md
index d98ff8a9..b7598365 100644
--- a/problems/0110.平衡二叉树.md
+++ b/problems/0110.平衡二叉树.md
@@ -208,7 +208,7 @@ int getHeight(TreeNode* node) {
```CPP
class Solution {
public:
- // 返回以该节点为根节点的二叉树的高度,如果不是二叉搜索树了则返回-1
+ // 返回以该节点为根节点的二叉树的高度,如果不是平衡二叉树了则返回-1
int getHeight(TreeNode* node) {
if (node == NULL) {
return 0;
From 4aad0f9ca58c0188248af5a1043a21722aae0129 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Wed, 18 May 2022 17:26:22 +0800
Subject: [PATCH 106/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=8F=89?=
=?UTF-8?q?=E6=A0=91=E7=9A=84=E8=BF=AD=E4=BB=A3=E9=81=8D=E5=8E=86.md=20Sca?=
=?UTF-8?q?la=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/二叉树的迭代遍历.md | 65 ++++++++++++++++++++++++++++++++++++
1 file changed, 65 insertions(+)
diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md
index 13ba5f1e..fac30f99 100644
--- a/problems/二叉树的迭代遍历.md
+++ b/problems/二叉树的迭代遍历.md
@@ -568,6 +568,71 @@ func inorderTraversal(_ root: TreeNode?) -> [Int] {
return result
}
```
+Scala:
+```scala
+// 前序遍历(迭代法)
+object Solution {
+ import scala.collection.mutable
+ def preorderTraversal(root: TreeNode): List[Int] = {
+ val res = mutable.ListBuffer[Int]()
+ if (root == null) return res.toList
+ // 声明一个栈,泛型为TreeNode
+ val stack = mutable.Stack[TreeNode]()
+ stack.push(root) // 先把根节点压入栈
+ while (!stack.isEmpty) {
+ var curNode = stack.pop()
+ res.append(curNode.value) // 先把这个值压入栈
+ // 如果当前节点的左右节点不为空,则入栈,先放右节点,再放左节点
+ if (curNode.right != null) stack.push(curNode.right)
+ if (curNode.left != null) stack.push(curNode.left)
+ }
+ res.toList
+ }
+}
+// 中序遍历(迭代法)
+object Solution {
+ import scala.collection.mutable
+ def inorderTraversal(root: TreeNode): List[Int] = {
+ val res = mutable.ArrayBuffer[Int]()
+ if (root == null) return res.toList
+ val stack = mutable.Stack[TreeNode]()
+ var curNode = root
+ // 将左节点都入栈,当遍历到最左(到空)的时候,再弹出栈顶元素,加入res
+ // 再把栈顶元素的右节点加进来,继续下一轮遍历
+ while (curNode != null || !stack.isEmpty) {
+ if (curNode != null) {
+ stack.push(curNode)
+ curNode = curNode.left
+ } else {
+ curNode = stack.pop()
+ res.append(curNode.value)
+ curNode = curNode.right
+ }
+ }
+ res.toList
+ }
+}
+
+// 后序遍历(迭代法)
+object Solution {
+ import scala.collection.mutable
+ def postorderTraversal(root: TreeNode): List[Int] = {
+ val res = mutable.ListBuffer[Int]()
+ if (root == null) return res.toList
+ val stack = mutable.Stack[TreeNode]()
+ stack.push(root)
+ while (!stack.isEmpty) {
+ val curNode = stack.pop()
+ res.append(curNode.value)
+ // 这次左节点先入栈,右节点再入栈
+ if(curNode.left != null) stack.push(curNode.left)
+ if(curNode.right != null) stack.push(curNode.right)
+ }
+ // 最后需要翻转List
+ res.reverse.toList
+ }
+}
+```
-----------------------
From b8b62ffc32de46005c4317150f952ad1aa483f5c Mon Sep 17 00:00:00 2001
From: 3Xpl0it3r
Date: Wed, 18 May 2022 18:31:37 +0800
Subject: [PATCH 107/162] =?UTF-8?q?=E6=A0=91=E6=B7=B1=E5=BA=A6=20rust?=
=?UTF-8?q?=E5=AE=9E=E7=8E=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0104.二叉树的最大深度.md | 27 +++++++++++++
problems/0111.二叉树的最小深度.md | 64 +++++++++++++++++++++++++++++++
2 files changed, 91 insertions(+)
diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md
index 2229a854..65a155fb 100644
--- a/problems/0104.二叉树的最大深度.md
+++ b/problems/0104.二叉树的最大深度.md
@@ -192,6 +192,33 @@ public:
};
```
+rust:
+```rust
+impl Solution {
+ pub fn max_depth(root: Option>>) -> i32 {
+ if root.is_none(){
+ return 0;
+ }
+ let mut max_depth: i32 = 0;
+ let mut stack = vec![root.unwrap()];
+ while !stack.is_empty() {
+ let num = stack.len();
+ for _i in 0..num{
+ let top = stack.remove(0);
+ if top.borrow_mut().left.is_some(){
+ stack.push(top.borrow_mut().left.take().unwrap());
+ }
+ if top.borrow_mut().right.is_some(){
+ stack.push(top.borrow_mut().right.take().unwrap());
+ }
+ }
+ max_depth+=1;
+ }
+ max_depth
+ }
+```
+
+
那么我们可以顺便解决一下n叉树的最大深度问题
# 559.n叉树的最大深度
diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md
index 224caa5e..b1331659 100644
--- a/problems/0111.二叉树的最小深度.md
+++ b/problems/0111.二叉树的最小深度.md
@@ -488,5 +488,69 @@ func minDepth(_ root: TreeNode?) -> Int {
}
```
+rust:
+```rust
+impl Solution {
+ pub fn min_depth(root: Option>>) -> i32 {
+ return Solution::bfs(root)
+ }
+
+ // 递归
+ pub fn dfs(node: Option>>) -> i32{
+ if node.is_none(){
+ return 0;
+ }
+ let parent = node.unwrap();
+ let left_child = parent.borrow_mut().left.take();
+ let right_child = parent.borrow_mut().right.take();
+ if left_child.is_none() && right_child.is_none(){
+ return 1;
+ }
+ let mut min_depth = i32::MAX;
+ if left_child.is_some(){
+ let left_depth = Solution::dfs(left_child);
+ if left_depth <= min_depth{
+ min_depth = left_depth
+ }
+ }
+ if right_child.is_some(){
+ let right_depth = Solution::dfs(right_child);
+ if right_depth <= min_depth{
+ min_depth = right_depth
+ }
+ }
+ min_depth + 1
+
+ }
+
+ // 迭代
+ pub fn bfs(node: Option>>) -> i32{
+ let mut min_depth = 0;
+ if node.is_none(){
+ return min_depth
+ }
+ let mut stack = vec![node.unwrap()];
+ while !stack.is_empty(){
+ min_depth += 1;
+ let num = stack.len();
+ for _i in 0..num{
+ let top = stack.remove(0);
+ let left_child = top.borrow_mut().left.take();
+ let right_child = top.borrow_mut().right.take();
+ if left_child.is_none() && right_child.is_none(){
+ return min_depth;
+ }
+ if left_child.is_some(){
+ stack.push(left_child.unwrap());
+ }
+ if right_child.is_some(){
+ stack.push(right_child.unwrap());
+ }
+ }
+ }
+ min_depth
+ }
+```
+
-----------------------
From 54d10fc3b893d50c278349c9de9d09bab5924ae7 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 19 May 2022 00:21:29 +0800
Subject: [PATCH 108/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880300.?=
=?UTF-8?q?=E6=9C=80=E9=95=BF=E4=B8=8A=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97?=
=?UTF-8?q?.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0300.最长上升子序列.md | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md
index f68edb5a..5ccb2d76 100644
--- a/problems/0300.最长上升子序列.md
+++ b/problems/0300.最长上升子序列.md
@@ -220,6 +220,27 @@ const lengthOfLIS = (nums) => {
};
```
+TypeScript
+
+```typescript
+function lengthOfLIS(nums: number[]): number {
+ /**
+ dp[i]: 前i个元素中,以nums[i]结尾,最长子序列的长度
+ */
+ const dp: number[] = new Array(nums.length).fill(1);
+ let resMax: number = 0;
+ for (let i = 0, length = nums.length; i < length; i++) {
+ for (let j = 0; j < i; j++) {
+ if (nums[i] > nums[j]) {
+ dp[i] = Math.max(dp[i], dp[j] + 1);
+ }
+ }
+ resMax = Math.max(resMax, dp[i]);
+ }
+ return resMax;
+};
+```
+
From 52a486101d0525074a7b1f6a54a98b5940f9ab50 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 19 May 2022 00:43:00 +0800
Subject: [PATCH 109/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880674.?=
=?UTF-8?q?=E6=9C=80=E9=95=BF=E8=BF=9E=E7=BB=AD=E9=80=92=E5=A2=9E=E5=BA=8F?=
=?UTF-8?q?=E5=88=97.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0674.最长连续递增序列.md | 39 +++++++++++++++++++++++++++++++
1 file changed, 39 insertions(+)
diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md
index 56e95d97..6ec4a6c7 100644
--- a/problems/0674.最长连续递增序列.md
+++ b/problems/0674.最长连续递增序列.md
@@ -319,6 +319,45 @@ const findLengthOfLCIS = (nums) => {
};
```
+TypeScript:
+
+> 动态规划:
+
+```typescript
+function findLengthOfLCIS(nums: number[]): number {
+ /**
+ dp[i]: 前i个元素,以nums[i]结尾,最长连续子序列的长度
+ */
+ const dp: number[] = new Array(nums.length).fill(1);
+ let resMax: number = 1;
+ for (let i = 1, length = nums.length; i < length; i++) {
+ if (nums[i] > nums[i - 1]) {
+ dp[i] = dp[i - 1] + 1;
+ }
+ resMax = Math.max(resMax, dp[i]);
+ }
+ return resMax;
+};
+```
+
+> 贪心:
+
+```typescript
+function findLengthOfLCIS(nums: number[]): number {
+ let resMax: number = 1;
+ let count: number = 1;
+ for (let i = 0, length = nums.length; i < length - 1; i++) {
+ if (nums[i] < nums[i + 1]) {
+ count++;
+ } else {
+ count = 1;
+ }
+ resMax = Math.max(resMax, count);
+ }
+ return resMax;
+};
+```
+
From 648014b28a54e953d335e822d7e7a5f98a82e3ea Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 10:19:22 +0800
Subject: [PATCH 110/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=8F=89?=
=?UTF-8?q?=E6=A0=91=E7=9A=84=E7=BB=9F=E4=B8=80=E8=BF=AD=E4=BB=A3=E6=B3=95?=
=?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/二叉树的统一迭代法.md | 74 ++++++++++++++++++++++++++++++++++
1 file changed, 74 insertions(+)
diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md
index f6edf586..9ca6ac39 100644
--- a/problems/二叉树的统一迭代法.md
+++ b/problems/二叉树的统一迭代法.md
@@ -591,6 +591,80 @@ function postorderTraversal(root: TreeNode | null): number[] {
return res;
};
```
+Scala:
+```scala
+// 前序遍历
+object Solution {
+ import scala.collection.mutable
+ def preorderTraversal(root: TreeNode): List[Int] = {
+ val res = mutable.ListBuffer[Int]()
+ val stack = mutable.Stack[TreeNode]()
+ if (root != null) stack.push(root)
+ while (!stack.isEmpty) {
+ var curNode = stack.top
+ if (curNode != null) {
+ stack.pop()
+ if (curNode.right != null) stack.push(curNode.right)
+ if (curNode.left != null) stack.push(curNode.left)
+ stack.push(curNode)
+ stack.push(null)
+ } else {
+ stack.pop()
+ res.append(stack.pop().value)
+ }
+ }
+ res.toList
+ }
+}
+// 中序遍历
+object Solution {
+ import scala.collection.mutable
+ def inorderTraversal(root: TreeNode): List[Int] = {
+ val res = mutable.ListBuffer[Int]()
+ val stack = mutable.Stack[TreeNode]()
+ if (root != null) stack.push(root)
+ while (!stack.isEmpty) {
+ var curNode = stack.top
+ if (curNode != null) {
+ stack.pop()
+ if (curNode.right != null) stack.push(curNode.right)
+ stack.push(curNode)
+ stack.push(null)
+ if (curNode.left != null) stack.push(curNode.left)
+ } else {
+ // 等于空的时候好办,弹出这个元素
+ stack.pop()
+ res.append(stack.pop().value)
+ }
+ }
+ res.toList
+ }
+}
+
+// 后序遍历
+object Solution {
+ import scala.collection.mutable
+ def postorderTraversal(root: TreeNode): List[Int] = {
+ val res = mutable.ListBuffer[Int]()
+ val stack = mutable.Stack[TreeNode]()
+ if (root != null) stack.push(root)
+ while (!stack.isEmpty) {
+ var curNode = stack.top
+ if (curNode != null) {
+ stack.pop()
+ stack.push(curNode)
+ stack.push(null)
+ if (curNode.right != null) stack.push(curNode.right)
+ if (curNode.left != null) stack.push(curNode.left)
+ } else {
+ stack.pop()
+ res.append(stack.pop().value)
+ }
+ }
+ res.toList
+ }
+}
+```
-----------------------
From 33ed3d980eecec6824fb5b9edad83d7b916c4142 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 10:35:55 +0800
Subject: [PATCH 111/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20102.=E4=BA=8C?=
=?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86?=
=?UTF-8?q?=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index ab8f2e57..5afce73a 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -298,6 +298,31 @@ func levelOrder(_ root: TreeNode?) -> [[Int]] {
return result
}
```
+Scala:
+```scala
+// 102.二叉树的层序遍历
+object Solution {
+ import scala.collection.mutable
+ def levelOrder(root: TreeNode): List[List[Int]] = {
+ val res = mutable.ListBuffer[List[Int]]()
+ if (root == null) return res.toList
+ val queue = mutable.Queue[TreeNode]() // 声明一个队列
+ queue.enqueue(root) // 把根节点加入queue
+ while (!queue.isEmpty) {
+ val tmp = mutable.ListBuffer[Int]()
+ val len = queue.size // 求出len的长度
+ for (i <- 0 until len) { // 从0到当前队列长度的所有节点都加入到结果集
+ val curNode = queue.dequeue()
+ tmp.append(curNode.value)
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ res.append(tmp.toList)
+ }
+ res.toList
+ }
+}
+```
**此时我们就掌握了二叉树的层序遍历了,那么如下九道力扣上的题目,只需要修改模板的两三行代码(不能再多了),便可打倒!**
From 04339562c7ce6c46dbd081551e51f36dcaf5fe8d Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 10:36:51 +0800
Subject: [PATCH 112/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20107.=E4=BA=8C?=
=?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E6=AC=A1=E9=81=8D=E5=8E=86?=
=?UTF-8?q?II=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index 5afce73a..e707ce27 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -553,6 +553,33 @@ func levelOrderBottom(_ root: TreeNode?) -> [[Int]] {
}
```
+Scala:
+```scala
+// 107.二叉树的层次遍历II
+object Solution {
+ import scala.collection.mutable
+ def levelOrderBottom(root: TreeNode): List[List[Int]] = {
+ val res = mutable.ListBuffer[List[Int]]()
+ if (root == null) return res.toList
+ val queue = mutable.Queue[TreeNode]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ val tmp = mutable.ListBuffer[Int]()
+ val len = queue.size
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ tmp.append(curNode.value)
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ res.append(tmp.toList)
+ }
+ // 最后翻转一下
+ res.reverse.toList
+ }
+}
+```
+
# 199.二叉树的右视图
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/)
From ba51a4947adb197fcc4551e3157c509795fd0a82 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 11:03:09 +0800
Subject: [PATCH 113/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20199.=E4=BA=8C?=
=?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=8F=B3=E8=A7=86=E5=9B=BE=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index ab8f2e57..b74f1a0b 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -750,6 +750,31 @@ func rightSideView(_ root: TreeNode?) -> [Int] {
}
```
+Scala:
+```scala
+// 199.二叉树的右视图
+object Solution {
+ import scala.collection.mutable
+ def rightSideView(root: TreeNode): List[Int] = {
+ val res = mutable.ListBuffer[Int]()
+ if (root == null) return res.toList
+ val queue = mutable.Queue[TreeNode]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ val len = queue.size
+ var curNode: TreeNode = null
+ for (i <- 0 until len) {
+ curNode = queue.dequeue()
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ res.append(curNode.value) // 把最后一个节点的值加入解集
+ }
+ res.toList // 最后需要把res转换为List,return关键字可以省略
+ }
+}
+```
+
# 637.二叉树的层平均值
[力扣题目链接](https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/)
From 0b88af0824b696be6d2f107adde3758f1df1c3f8 Mon Sep 17 00:00:00 2001
From: lizhendong128
Date: Thu, 19 May 2022 11:08:59 +0800
Subject: [PATCH 114/162] =?UTF-8?q?=E4=BF=AE=E6=94=B90150=E9=80=86?=
=?UTF-8?q?=E6=B3=A2=E5=85=B0=E8=A1=A8=E8=BE=BE=E5=BC=8F=E6=B1=82=E5=80=BC?=
=?UTF-8?q?=20Java=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
将for循环改为for each,使代码更加简洁。因为循环除了对token进行遍历,i并没有其他用途。
---
problems/0150.逆波兰表达式求值.md | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md
index fd3d69aa..6ce7e2f9 100644
--- a/problems/0150.逆波兰表达式求值.md
+++ b/problems/0150.逆波兰表达式求值.md
@@ -136,19 +136,19 @@ java:
class Solution {
public int evalRPN(String[] tokens) {
Deque stack = new LinkedList();
- for (int i = 0; i < tokens.length; ++i) {
- if ("+".equals(tokens[i])) { // leetcode 内置jdk的问题,不能使用==判断字符串是否相等
+ for (String s : tokens) {
+ if ("+".equals(s)) { // leetcode 内置jdk的问题,不能使用==判断字符串是否相等
stack.push(stack.pop() + stack.pop()); // 注意 - 和/ 需要特殊处理
- } else if ("-".equals(tokens[i])) {
+ } else if ("-".equals(s)) {
stack.push(-stack.pop() + stack.pop());
- } else if ("*".equals(tokens[i])) {
+ } else if ("*".equals(s)) {
stack.push(stack.pop() * stack.pop());
- } else if ("/".equals(tokens[i])) {
+ } else if ("/".equals(s)) {
int temp1 = stack.pop();
int temp2 = stack.pop();
stack.push(temp2 / temp1);
} else {
- stack.push(Integer.valueOf(tokens[i]));
+ stack.push(Integer.valueOf(s));
}
}
return stack.pop();
From 9af80d3007aed88bd8d09538ab6710218c3e9dfd Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 11:10:07 +0800
Subject: [PATCH 115/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20637.=E4=BA=8C?=
=?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=B9=B3=E5=9D=87=E5=80=BC?=
=?UTF-8?q?=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index b74f1a0b..a99449fb 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -1006,6 +1006,30 @@ func averageOfLevels(_ root: TreeNode?) -> [Double] {
return result
}
```
+Scala:
+```scala
+// 637.二叉树的层平均值
+object Solution {
+ import scala.collection.mutable
+ def averageOfLevels(root: TreeNode): Array[Double] = {
+ val res = mutable.ArrayBuffer[Double]()
+ val queue = mutable.Queue[TreeNode]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ var sum = 0.0
+ var len = queue.size
+ for (i <- 0 until len) {
+ var curNode = queue.dequeue()
+ sum += curNode.value // 累加该层的值
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ res.append(sum / len) // 平均值即为sum/len
+ }
+ res.toArray // 最后需要转换为Array,return关键字可以省略
+ }
+}
+```
# 429.N叉树的层序遍历
From c922fbc0e3ee16bbd0f3406227ce51a44cfe636d Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 12:19:10 +0800
Subject: [PATCH 116/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20429.N=E5=8F=89?=
=?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=20Scala?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index a99449fb..6964e1f0 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -1274,6 +1274,34 @@ func levelOrder(_ root: Node?) -> [[Int]] {
}
```
+Scala:
+```scala
+// 429.N叉树的层序遍历
+object Solution {
+ import scala.collection.mutable
+ def levelOrder(root: Node): List[List[Int]] = {
+ val res = mutable.ListBuffer[List[Int]]()
+ if (root == null) return res.toList
+ val queue = mutable.Queue[Node]()
+ queue.enqueue(root) // 根节点入队
+ while (!queue.isEmpty) {
+ val tmp = mutable.ListBuffer[Int]() // 存储每层节点
+ val len = queue.size
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ tmp.append(curNode.value) // 将该节点的值加入tmp
+ // 循环遍历该节点的子节点,加入队列
+ for (child <- curNode.children) {
+ queue.enqueue(child)
+ }
+ }
+ res.append(tmp.toList) // 将该层的节点放到结果集
+ }
+ res.toList
+ }
+}
+```
+
# 515.在每个树行中找最大值
[力扣题目链接](https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/)
From 80301657b305bcbd614d5294b1d483d31419755f Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 12:29:12 +0800
Subject: [PATCH 117/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20515.=E5=9C=A8?=
=?UTF-8?q?=E6=AF=8F=E4=B8=AA=E6=A0=91=E8=A1=8C=E4=B8=AD=E6=89=BE=E6=9C=80?=
=?UTF-8?q?=E5=A4=A7=E5=80=BC=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index ab8f2e57..db27c73d 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -1433,6 +1433,32 @@ func largestValues(_ root: TreeNode?) -> [Int] {
}
```
+Scala:
+```scala
+// 515.在每个树行中找最大值
+object Solution {
+ import scala.collection.mutable
+ def largestValues(root: TreeNode): List[Int] = {
+ val res = mutable.ListBuffer[Int]()
+ if (root == null) return res.toList
+ val queue = mutable.Queue[TreeNode]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ var max = Int.MinValue // 初始化max为系统最小值
+ val len = queue.size
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ max = math.max(max, curNode.value) // 对比求解最大值
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ res.append(max) // 将最大值放入结果集
+ }
+ res.toList
+ }
+}
+```
+
# 116.填充每个节点的下一个右侧节点指针
[力扣题目链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/)
From a3179499d03b05594b8808a1d11a0ab22048cf32 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 12:58:52 +0800
Subject: [PATCH 118/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20116.=E5=A1=AB?=
=?UTF-8?q?=E5=85=85=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B?=
=?UTF-8?q?=E4=B8=80=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87?=
=?UTF-8?q?=E9=92=88=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index db27c73d..18fdfcb3 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -1718,6 +1718,35 @@ func connect(_ root: Node?) -> Node? {
}
```
+Scala:
+```scala
+// 116.填充每个节点的下一个右侧节点指针
+object Solution {
+ import scala.collection.mutable
+
+ def connect(root: Node): Node = {
+ if (root == null) return root
+ val queue = mutable.Queue[Node]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ val len = queue.size
+ val tmp = mutable.ListBuffer[Node]()
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ tmp.append(curNode)
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ // 处理next指针
+ for (i <- 0 until tmp.size - 1) {
+ tmp(i).next = tmp(i + 1)
+ }
+ tmp(tmp.size-1).next = null
+ }
+ root
+ }
+}
+```
# 117.填充每个节点的下一个右侧节点指针II
[力扣题目链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/)
From 7a62a75e399325cf439eebf507e8ce2d576e618d Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 12:59:45 +0800
Subject: [PATCH 119/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20117.=E5=A1=AB?=
=?UTF-8?q?=E5=85=85=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B?=
=?UTF-8?q?=E4=B8=80=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87?=
=?UTF-8?q?=E9=92=88II=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index 18fdfcb3..a2130f7e 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -1998,6 +1998,35 @@ func connect(_ root: Node?) -> Node? {
}
```
+Scala:
+```scala
+// 117.填充每个节点的下一个右侧节点指针II
+object Solution {
+ import scala.collection.mutable
+
+ def connect(root: Node): Node = {
+ if (root == null) return root
+ val queue = mutable.Queue[Node]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ val len = queue.size
+ val tmp = mutable.ListBuffer[Node]()
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ tmp.append(curNode)
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ // 处理next指针
+ for (i <- 0 until tmp.size - 1) {
+ tmp(i).next = tmp(i + 1)
+ }
+ tmp(tmp.size-1).next = null
+ }
+ root
+ }
+}
+```
# 104.二叉树的最大深度
[力扣题目链接](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/)
From 32f0599243e7e9585a9b18a8b36fa0e50f120a24 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 13:38:22 +0800
Subject: [PATCH 120/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20104.=E4=BA=8C?=
=?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6?=
=?UTF-8?q?=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index ab8f2e57..95a6b5d6 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -2160,6 +2160,30 @@ func maxDepth(_ root: TreeNode?) -> Int {
}
```
+Scala:
+```scala
+// 104.二叉树的最大深度
+object Solution {
+ import scala.collection.mutable
+ def maxDepth(root: TreeNode): Int = {
+ if (root == null) return 0
+ val queue = mutable.Queue[TreeNode]()
+ queue.enqueue(root)
+ var depth = 0
+ while (!queue.isEmpty) {
+ val len = queue.length
+ depth += 1
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ }
+ depth
+ }
+}
+```
+
# 111.二叉树的最小深度
[力扣题目链接](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/)
From f5c5a58b137adad5490c04b57f82953101789999 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Thu, 19 May 2022 13:42:12 +0800
Subject: [PATCH 121/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20111.=E4=BA=8C?=
=?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6?=
=?UTF-8?q?=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0102.二叉树的层序遍历.md | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md
index 95a6b5d6..b411816a 100644
--- a/problems/0102.二叉树的层序遍历.md
+++ b/problems/0102.二叉树的层序遍历.md
@@ -2403,6 +2403,30 @@ func minDepth(_ root: TreeNode?) -> Int {
}
```
+Scala:
+```scala
+// 111.二叉树的最小深度
+object Solution {
+ import scala.collection.mutable
+ def minDepth(root: TreeNode): Int = {
+ if (root == null) return 0
+ var depth = 0
+ val queue = mutable.Queue[TreeNode]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ depth += 1
+ val len = queue.size
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ if (curNode.left == null && curNode.right == null) return depth
+ }
+ }
+ depth
+ }
+}
+```
# 总结
From afcf6cd5a1093c3bc4f525b211858da02e4c47c6 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 19 May 2022 15:03:09 +0800
Subject: [PATCH 122/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880718.?=
=?UTF-8?q?=E6=9C=80=E9=95=BF=E9=87=8D=E5=A4=8D=E5=AD=90=E6=95=B0=E7=BB=84?=
=?UTF-8?q?.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0718.最长重复子数组.md | 50 +++++++++++++++++++++++++++++++++
1 file changed, 50 insertions(+)
diff --git a/problems/0718.最长重复子数组.md b/problems/0718.最长重复子数组.md
index 87b1492a..0b7b5199 100644
--- a/problems/0718.最长重复子数组.md
+++ b/problems/0718.最长重复子数组.md
@@ -297,6 +297,56 @@ const findLength = (nums1, nums2) => {
}
```
+TypeScript:
+
+> 动态规划:
+
+```typescript
+function findLength(nums1: number[], nums2: number[]): number {
+ /**
+ dp[i][j]:nums[i-1]和nums[j-1]结尾,最长重复子数组的长度
+ */
+ const length1: number = nums1.length,
+ length2: number = nums2.length;
+ const dp: number[][] = new Array(length1 + 1).fill(0)
+ .map(_ => new Array(length2 + 1).fill(0));
+ let resMax: number = 0;
+ for (let i = 1; i <= length1; i++) {
+ for (let j = 1; j <= length2; j++) {
+ if (nums1[i - 1] === nums2[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ resMax = Math.max(resMax, dp[i][j]);
+ }
+ }
+ }
+ return resMax;
+};
+```
+
+> 滚动数组:
+
+```typescript
+function findLength(nums1: number[], nums2: number[]): number {
+ const length1: number = nums1.length,
+ length2: number = nums2.length;
+ const dp: number[] = new Array(length1 + 1).fill(0);
+ let resMax: number = 0;
+ for (let i = 1; i <= length1; i++) {
+ for (let j = length2; j >= 1; j--) {
+ if (nums1[i - 1] === nums2[j - 1]) {
+ dp[j] = dp[j - 1] + 1;
+ resMax = Math.max(resMax, dp[j]);
+ } else {
+ dp[j] = 0;
+ }
+ }
+ }
+ return resMax;
+};
+```
+
+
+
-----------------------
From a4b024705b276e5cf69a2a521af8b923a32daaca Mon Sep 17 00:00:00 2001
From: xuxiaomeng <961592690@qq.com>
Date: Thu, 19 May 2022 20:25:16 +0800
Subject: [PATCH 123/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A00704.=E4=BA=8C?=
=?UTF-8?q?=E5=88=86=E6=9F=A5=E6=89=BE=20Kotlin=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0704.二分查找.md | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md
index 55625130..9173d1da 100644
--- a/problems/0704.二分查找.md
+++ b/problems/0704.二分查找.md
@@ -611,6 +611,38 @@ public class Solution{
}
```
+**Kotlin:**
+```Kotlin
+// (版本一)左闭右开区间
+class Solution {
+ fun search(nums: IntArray, target: Int): Int {
+ var left = 0
+ var right = nums.size // [left,right) 右侧为开区间,right 设置为 nums.size
+ while (left < right) {
+ val mid = (left + right) / 2
+ if (nums[mid] < target) left = mid + 1
+ else if (nums[mid] > target) right = mid // 代码的核心,循环中 right 是开区间,这里也应是开区间
+ else return mid
+ }
+ return -1 // 没有找到 target ,返回 -1
+ }
+}
+// (版本二)左闭右闭区间
+class Solution {
+ fun search(nums: IntArray, target: Int): Int {
+ var left = 0
+ var right = nums.size - 1 // [left,right] 右侧为闭区间,right 设置为 nums.size - 1
+ while (left <= right) {
+ val mid = (left + right) / 2
+ if (nums[mid] < target) left = mid + 1
+ else if (nums[mid] > target) right = mid - 1 // 代码的核心,循环中 right 是闭区间,这里也应是闭区间
+ else return mid
+ }
+ return -1 // 没有找到 target ,返回 -1
+ }
+}
+```
+
-----------------------
From 568a569f0572cd500c152c7d836bc3aea42a59ad Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 19 May 2022 20:39:58 +0800
Subject: [PATCH 124/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=881143.?=
=?UTF-8?q?=E6=9C=80=E9=95=BF=E5=85=AC=E5=85=B1=E5=AD=90=E5=BA=8F=E5=88=97?=
=?UTF-8?q?.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/1143.最长公共子序列.md | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md
index ecedf89b..d58330ec 100644
--- a/problems/1143.最长公共子序列.md
+++ b/problems/1143.最长公共子序列.md
@@ -236,6 +236,32 @@ const longestCommonSubsequence = (text1, text2) => {
};
```
+TypeScript:
+
+```typescript
+function longestCommonSubsequence(text1: string, text2: string): number {
+ /**
+ dp[i][j]: text1中前i-1个和text2中前j-1个,最长公共子序列的长度
+ */
+ const length1: number = text1.length,
+ length2: number = text2.length;
+ const dp: number[][] = new Array(length1 + 1).fill(0)
+ .map(_ => new Array(length2 + 1).fill(0));
+ for (let i = 1; i <= length1; i++) {
+ for (let j = 1; j <= length2; j++) {
+ if (text1[i - 1] === text2[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ } else {
+ dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
+ }
+ }
+ }
+ return dp[length1][length2];
+};
+```
+
+
+
-----------------------
From b3335f78a9a5c0910577835f8e61069594a23a0f Mon Sep 17 00:00:00 2001
From: zhouchaoyu1
Date: Thu, 19 May 2022 20:47:08 +0800
Subject: [PATCH 125/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20763.=E5=88=92?=
=?UTF-8?q?=E5=88=86=E5=AD=97=E6=AF=8D=E5=8C=BA=E9=97=B4=20=E8=A1=A5?=
=?UTF-8?q?=E5=85=85=E6=80=9D=E8=B7=AF=E7=9A=84Java=E4=BB=A3=E7=A0=81?=
=?UTF-8?q?=E5=AE=9E=E7=8E=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0763.划分字母区间.md | 65 +++++++++++++++++++++++++++++++++++
1 file changed, 65 insertions(+)
diff --git a/problems/0763.划分字母区间.md b/problems/0763.划分字母区间.md
index 2210cffa..2f4d1b48 100644
--- a/problems/0763.划分字母区间.md
+++ b/problems/0763.划分字母区间.md
@@ -158,6 +158,71 @@ class Solution {
return list;
}
}
+
+class Solution{
+ /*解法二: 上述c++补充思路的Java代码实现*/
+
+ public int[][] findPartitions(String s) {
+ List temp = new ArrayList<>();
+ int[][] hash = new int[26][2];//26个字母2列 表示该字母对应的区间
+
+ for (int i = 0; i < s.length(); i++) {
+ //更新字符c对应的位置i
+ char c = s.charAt(i);
+ if (hash[c - 'a'][0] == 0) hash[c - 'a'][0] = i;
+
+ hash[c - 'a'][1] = i;
+
+ //第一个元素区别对待一下
+ hash[s.charAt(0) - 'a'][0] = 0;
+ }
+
+
+ List> h = new LinkedList<>();
+ //组装区间
+ for (int i = 0; i < 26; i++) {
+ //if (hash[i][0] != hash[i][1]) {
+ temp.clear();
+ temp.add(hash[i][0]);
+ temp.add(hash[i][1]);
+ //System.out.println(temp);
+ h.add(new ArrayList<>(temp));
+ // }
+ }
+ // System.out.println(h);
+ // System.out.println(h.size());
+ int[][] res = new int[h.size()][2];
+ for (int i = 0; i < h.size(); i++) {
+ List list = h.get(i);
+ res[i][0] = list.get(0);
+ res[i][1] = list.get(1);
+ }
+
+ return res;
+
+ }
+
+ public List partitionLabels(String s) {
+ int[][] partitions = findPartitions(s);
+ List res = new ArrayList<>();
+ Arrays.sort(partitions, (o1, o2) -> Integer.compare(o1[0], o2[0]));
+ int right = partitions[0][1];
+ int left = 0;
+ for (int i = 0; i < partitions.length; i++) {
+ if (partitions[i][0] > right) {
+ //左边界大于右边界即可纪委一次分割
+ res.add(right - left + 1);
+ left = partitions[i][0];
+ }
+ right = Math.max(right, partitions[i][1]);
+
+ }
+ //最右端
+ res.add(right - left + 1);
+ return res;
+
+ }
+}
```
### Python
From 30c1be11ff9ef77ff6cf0294f37b09ae50ea4619 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 19 May 2022 21:26:54 +0800
Subject: [PATCH 126/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=881035.?=
=?UTF-8?q?=E4=B8=8D=E7=9B=B8=E4=BA=A4=E7=9A=84=E7=BA=BF.md=EF=BC=89?=
=?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/1035.不相交的线.md | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/problems/1035.不相交的线.md b/problems/1035.不相交的线.md
index 279ed816..4463c5f7 100644
--- a/problems/1035.不相交的线.md
+++ b/problems/1035.不相交的线.md
@@ -183,6 +183,30 @@ const maxUncrossedLines = (nums1, nums2) => {
};
```
+TypeScript:
+
+```typescript
+function maxUncrossedLines(nums1: number[], nums2: number[]): number {
+ /**
+ dp[i][j]: nums1前i-1个,nums2前j-1个,最大连线数
+ */
+ const length1: number = nums1.length,
+ length2: number = nums2.length;
+ const dp: number[][] = new Array(length1 + 1).fill(0)
+ .map(_ => new Array(length2 + 1).fill(0));
+ for (let i = 1; i <= length1; i++) {
+ for (let j = 1; j <= length2; j++) {
+ if (nums1[i - 1] === nums2[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ } else {
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
+ }
+ }
+ }
+ return dp[length1][length2];
+};
+```
+
From 4d2b80ce7508553923c99a7786521c018c24ff8a Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Thu, 19 May 2022 21:59:33 +0800
Subject: [PATCH 127/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880053.?=
=?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=AD=90=E5=BA=8F=E5=92=8C=E5=8A=A8=E6=80=81?=
=?UTF-8?q?=E8=A7=84=E5=88=92.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?=
=?UTF-8?q?ript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0053.最大子序和(动态规划).md | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/problems/0053.最大子序和(动态规划).md b/problems/0053.最大子序和(动态规划).md
index 4c883cb6..99aa7acf 100644
--- a/problems/0053.最大子序和(动态规划).md
+++ b/problems/0053.最大子序和(动态规划).md
@@ -186,6 +186,24 @@ const maxSubArray = nums => {
};
```
+TypeScript:
+
+```typescript
+function maxSubArray(nums: number[]): number {
+ /**
+ dp[i]:以nums[i]结尾的最大和
+ */
+ const dp: number[] = []
+ dp[0] = nums[0];
+ let resMax: number = 0;
+ for (let i = 1; i < nums.length; i++) {
+ dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
+ resMax = Math.max(resMax, dp[i]);
+ }
+ return resMax;
+};
+```
+
-----------------------
From 8759349af0001c6ee2f05ceece9cc0e331fbc08a Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Fri, 20 May 2022 00:35:32 +0800
Subject: [PATCH 128/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880392.?=
=?UTF-8?q?=E5=88=A4=E6=96=AD=E5=AD=90=E5=BA=8F=E5=88=97.md=EF=BC=89?=
=?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0392.判断子序列.md | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/problems/0392.判断子序列.md b/problems/0392.判断子序列.md
index 671576f7..3f7eb11d 100644
--- a/problems/0392.判断子序列.md
+++ b/problems/0392.判断子序列.md
@@ -201,7 +201,32 @@ const isSubsequence = (s, t) => {
};
```
+TypeScript:
+
+```typescript
+function isSubsequence(s: string, t: string): boolean {
+ /**
+ dp[i][j]: s的前i-1个,t的前j-1个,最长公共子序列的长度
+ */
+ const sLen: number = s.length,
+ tLen: number = t.length;
+ const dp: number[][] = new Array(sLen + 1).fill(0)
+ .map(_ => new Array(tLen + 1).fill(0));
+ for (let i = 1; i <= sLen; i++) {
+ for (let j = 1; j <= tLen; j++) {
+ if (s[i - 1] === t[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ } else {
+ dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
+ }
+ }
+ }
+ return dp[sLen][tLen] === s.length;
+};
+```
+
Go:
+
```go
func isSubsequence(s string, t string) bool {
dp := make([][]int,len(s)+1)
From 4eefc546c62d0b5d63f08d1b51e5603ee722d7d5 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Fri, 20 May 2022 13:41:23 +0800
Subject: [PATCH 129/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880115.?=
=?UTF-8?q?=E4=B8=8D=E5=90=8C=E7=9A=84=E5=AD=90=E5=BA=8F=E5=88=97.md?=
=?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0115.不同的子序列.md | 30 ++++++++++++++++++++++++++++++
1 file changed, 30 insertions(+)
diff --git a/problems/0115.不同的子序列.md b/problems/0115.不同的子序列.md
index 0f762969..ca66e20d 100644
--- a/problems/0115.不同的子序列.md
+++ b/problems/0115.不同的子序列.md
@@ -267,6 +267,36 @@ const numDistinct = (s, t) => {
};
```
+TypeScript:
+
+```typescript
+function numDistinct(s: string, t: string): number {
+ /**
+ dp[i][j]: s前i个字符,t前j个字符,s子序列中t出现的个数
+ dp[0][0]=1, 表示s前0个字符为'',t前0个字符为''
+ */
+ const sLen: number = s.length,
+ tLen: number = t.length;
+ const dp: number[][] = new Array(sLen + 1).fill(0)
+ .map(_ => new Array(tLen + 1).fill(0));
+ for (let m = 0; m < sLen; m++) {
+ dp[m][0] = 1;
+ }
+ for (let i = 1; i <= sLen; i++) {
+ for (let j = 1; j <= tLen; j++) {
+ if (s[i - 1] === t[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
+ } else {
+ dp[i][j] = dp[i - 1][j];
+ }
+ }
+ }
+ return dp[sLen][tLen];
+};
+```
+
+
+
-----------------------
From 58c4ad4947506310ef7c05d9603972af684c9b96 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Fri, 20 May 2022 15:11:12 +0800
Subject: [PATCH 130/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880583.?=
=?UTF-8?q?=E4=B8=A4=E4=B8=AA=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=9A=84=E5=88=A0?=
=?UTF-8?q?=E9=99=A4=E6=93=8D=E4=BD=9C.md=EF=BC=89=EF=BC=9A=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0583.两个字符串的删除操作.md | 61 +++++++++++++++++++++++++++
1 file changed, 61 insertions(+)
diff --git a/problems/0583.两个字符串的删除操作.md b/problems/0583.两个字符串的删除操作.md
index 53c1a125..00f11700 100644
--- a/problems/0583.两个字符串的删除操作.md
+++ b/problems/0583.两个字符串的删除操作.md
@@ -229,6 +229,67 @@ const minDistance = (word1, word2) => {
};
```
+TypeScript:
+
+> dp版本一:
+
+```typescript
+function minDistance(word1: string, word2: string): number {
+ /**
+ dp[i][j]: word1前i个字符,word2前j个字符,所需最小步数
+ dp[0][0]=0: word1前0个字符为'', word2前0个字符为''
+ */
+ const length1: number = word1.length,
+ length2: number = word2.length;
+ const dp: number[][] = new Array(length1 + 1).fill(0)
+ .map(_ => new Array(length2 + 1).fill(0));
+ for (let i = 0; i <= length1; i++) {
+ dp[i][0] = i;
+ }
+ for (let i = 0; i <= length2; i++) {
+ dp[0][i] = i;
+ }
+ for (let i = 1; i <= length1; i++) {
+ for (let j = 1; j <= length2; j++) {
+ if (word1[i - 1] === word2[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1];
+ } else {
+ dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1;
+ }
+ }
+ }
+ return dp[length1][length2];
+};
+```
+
+> dp版本二:
+
+```typescript
+function minDistance(word1: string, word2: string): number {
+ /**
+ dp[i][j]: word1前i个字符,word2前j个字符,最长公共子序列的长度
+ dp[0][0]=0: word1前0个字符为'', word2前0个字符为''
+ */
+ const length1: number = word1.length,
+ length2: number = word2.length;
+ const dp: number[][] = new Array(length1 + 1).fill(0)
+ .map(_ => new Array(length2 + 1).fill(0));
+ for (let i = 1; i <= length1; i++) {
+ for (let j = 1; j <= length2; j++) {
+ if (word1[i - 1] === word2[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ } else {
+ dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
+ }
+ }
+ }
+ const maxLen: number = dp[length1][length2];
+ return length1 + length2 - maxLen * 2;
+};
+```
+
+
+
-----------------------
From fa3a45c3dbd3cb58b9c0027cb2c8fe9e7727a439 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Fri, 20 May 2022 16:33:34 +0800
Subject: [PATCH 131/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880072.?=
=?UTF-8?q?=E7=BC=96=E8=BE=91=E8=B7=9D=E7=A6=BB.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0072.编辑距离.md | 37 +++++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)
diff --git a/problems/0072.编辑距离.md b/problems/0072.编辑距离.md
index 3802c228..530774ee 100644
--- a/problems/0072.编辑距离.md
+++ b/problems/0072.编辑距离.md
@@ -327,5 +327,42 @@ const minDistance = (word1, word2) => {
};
```
+TypeScript:
+
+```typescript
+function minDistance(word1: string, word2: string): number {
+ /**
+ dp[i][j]: word1前i个字符,word2前j个字符,最少操作数
+ dp[0][0]=0:表示word1前0个字符为'', word2前0个字符为''
+ */
+ const length1: number = word1.length,
+ length2: number = word2.length;
+ const dp: number[][] = new Array(length1 + 1).fill(0)
+ .map(_ => new Array(length2 + 1).fill(0));
+ for (let i = 0; i <= length1; i++) {
+ dp[i][0] = i;
+ }
+ for (let i = 0; i <= length2; i++) {
+ dp[0][i] = i;
+ }
+ for (let i = 1; i <= length1; i++) {
+ for (let j = 1; j <= length2; j++) {
+ if (word1[i - 1] === word2[j - 1]) {
+ dp[i][j] = dp[i - 1][j - 1];
+ } else {
+ dp[i][j] = Math.min(
+ dp[i - 1][j],
+ dp[i][j - 1],
+ dp[i - 1][j - 1]
+ ) + 1;
+ }
+ }
+ }
+ return dp[length1][length2];
+};
+```
+
+
+
-----------------------
From be7d6e1325009d5f404c8abeaae0cbed49ed2303 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 20 May 2022 19:36:10 +0800
Subject: [PATCH 132/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200226.=E7=BF=BB?=
=?UTF-8?q?=E8=BD=AC=E4=BA=8C=E5=8F=89=E6=A0=91.md=20Scala=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0226.翻转二叉树.md | 48 +++++++++++++++++++++++++++++++++++++
1 file changed, 48 insertions(+)
diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md
index a3ebe24d..e378cbc1 100644
--- a/problems/0226.翻转二叉树.md
+++ b/problems/0226.翻转二叉树.md
@@ -820,5 +820,53 @@ func invertTree(_ root: TreeNode?) -> TreeNode? {
}
```
+### Scala
+
+深度优先遍历(前序遍历):
+```scala
+object Solution {
+ def invertTree(root: TreeNode): TreeNode = {
+ if (root == null) return root
+ // 递归
+ def process(node: TreeNode): Unit = {
+ if (node == null) return
+ // 翻转节点
+ val curNode = node.left
+ node.left = node.right
+ node.right = curNode
+ process(node.left)
+ process(node.right)
+ }
+ process(root)
+ root
+ }
+}
+```
+
+广度优先遍历(层序遍历):
+```scala
+object Solution {
+ import scala.collection.mutable
+ def invertTree(root: TreeNode): TreeNode = {
+ if (root == null) return root
+ val queue = mutable.Queue[TreeNode]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ val len = queue.size
+ for (i <- 0 until len) {
+ var curNode = queue.dequeue()
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ // 翻转
+ var tmpNode = curNode.left
+ curNode.left = curNode.right
+ curNode.right = tmpNode
+ }
+ }
+ root
+ }
+}
+```
+
-----------------------
From 81d4685e36603ec59e3e02d8243f60e660081541 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Fri, 20 May 2022 21:12:54 +0800
Subject: [PATCH 133/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200101.=E5=AF=B9?=
=?UTF-8?q?=E7=A7=B0=E4=BA=8C=E5=8F=89=E6=A0=91.md=20Scala=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0101.对称二叉树.md | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md
index e4e232c8..97ca0685 100644
--- a/problems/0101.对称二叉树.md
+++ b/problems/0101.对称二叉树.md
@@ -725,5 +725,25 @@ func isSymmetric3(_ root: TreeNode?) -> Bool {
}
```
+## Scala
+
+递归:
+```scala
+object Solution {
+ def isSymmetric(root: TreeNode): Boolean = {
+ if (root == null) return true // 如果等于空直接返回true
+ def compare(left: TreeNode, right: TreeNode): Boolean = {
+ if (left == null && right == null) return true // 如果左右都为空,则为true
+ if (left == null && right != null) return false // 如果左空右不空,不对称,返回false
+ if (left != null && right == null) return false // 如果左不空右空,不对称,返回false
+ // 如果左右的值相等,并且往下递归
+ left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
+ }
+ // 分别比较左子树和右子树
+ compare(root.left, root.right)
+ }
+}
+```
+
-----------------------
From e7529aa31bf39bb1a3966ad8bd5fcbaa730b6447 Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Sat, 21 May 2022 09:14:39 +0800
Subject: [PATCH 134/162] =?UTF-8?q?=E9=87=8D=E5=86=99=200216.=E7=BB=84?=
=?UTF-8?q?=E5=90=88=E6=80=BB=E5=92=8CIII=20JavaScript=20=E7=89=88?=
=?UTF-8?q?=E6=9C=AC=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
原代码冗余,建议重写
---
problems/0216.组合总和III.md | 45 +++++++++++++++---------------------
1 file changed, 18 insertions(+), 27 deletions(-)
diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md
index 32b1347e..66ca7ff7 100644
--- a/problems/0216.组合总和III.md
+++ b/problems/0216.组合总和III.md
@@ -360,39 +360,30 @@ func backTree(n,k,startIndex int,track *[]int,result *[][]int){
## javaScript
```js
-// 等差数列
-var maxV = k => k * (9 + 10 - k) / 2;
-var minV = k => k * (1 + k) / 2;
+/**
+ * @param {number} k
+ * @param {number} n
+ * @return {number[][]}
+ */
var combinationSum3 = function(k, n) {
- if (k > 9 || k < 1) return [];
- // if (n > maxV(k) || n < minV(k)) return [];
- // if (n === maxV(k)) return [Array.from({length: k}).map((v, i) => 9 - i)];
- // if (n === minV(k)) return [Array.from({length: k}).map((v, i) => i + 1)];
-
- const res = [], path = [];
- backtracking(k, n, 1, 0);
- return res;
- function backtracking(k, n, i, sum){
- const len = path.length;
- if (len > k || sum > n) return;
- if (maxV(k - len) < n - sum) return;
- if (minV(k - len) > n - sum) return;
-
- if(len === k && sum == n) {
- res.push(Array.from(path));
+ const backtrack = (start) => {
+ const l = path.length;
+ if (l === k) {
+ const sum = path.reduce((a, b) => a + b);
+ if (sum === n) {
+ res.push([...path]);
+ }
return;
}
-
- const min = Math.min(n - sum, 9 + len - k + 1);
-
- for(let a = i; a <= min; a++) {
- path.push(a);
- sum += a;
- backtracking(k, n, a + 1, sum);
+ for (let i = start; i <= 9 - (k - l) + 1; i++) {
+ path.push(i);
+ backtrack(i + 1);
path.pop();
- sum -= a;
}
}
+ let res = [], path = [];
+ backtrack(1);
+ return res;
};
```
From b4873836bacc8a65b84e8f9a7e8da7fd5d7dcd58 Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Sat, 21 May 2022 09:45:03 +0800
Subject: [PATCH 135/162] =?UTF-8?q?=E7=BA=A0=E6=AD=A3=200131=20=E5=88=86?=
=?UTF-8?q?=E5=89=B2=E5=9B=9E=E6=96=87=E4=B8=B2=20JavaScript=20=E7=89=88?=
=?UTF-8?q?=E6=9C=AC=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
String 实例方法 substr 已弃用,请换成 slice
---
problems/0131.分割回文串.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md
index 7a702898..6a370fb4 100644
--- a/problems/0131.分割回文串.md
+++ b/problems/0131.分割回文串.md
@@ -442,7 +442,7 @@ var partition = function(s) {
}
for(let j = i; j < len; j++) {
if(!isPalindrome(s, i, j)) continue;
- path.push(s.substr(i, j - i + 1));
+ path.push(s.slice(i, j + 1));
backtracking(j + 1);
path.pop();
}
From ab6693d4b44e11dcf51771f5004e11e33c68c2cf Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Sat, 21 May 2022 09:57:03 +0800
Subject: [PATCH 136/162] =?UTF-8?q?=E7=BA=A0=E6=AD=A3=200093.=E5=A4=8D?=
=?UTF-8?q?=E5=88=B6IP=E5=9C=B0=E5=9D=80=20JavaScript=20=E7=89=88=E6=9C=AC?=
=?UTF-8?q?=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
String 实例 substr 方法已弃用,请使用 slice 方法
---
problems/0093.复原IP地址.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md
index 6401824b..d5eaa8ab 100644
--- a/problems/0093.复原IP地址.md
+++ b/problems/0093.复原IP地址.md
@@ -444,7 +444,7 @@ var restoreIpAddresses = function(s) {
return;
}
for(let j = i; j < s.length; j++) {
- const str = s.substr(i, j - i + 1);
+ const str = s.slice(i, j + 1);
if(str.length > 3 || +str > 255) break;
if(str.length > 1 && str[0] === "0") break;
path.push(str);
From fd194bd52fc58a22cf38627c3a6bc7d4e4335a11 Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Sat, 21 May 2022 10:06:05 +0800
Subject: [PATCH 137/162] =?UTF-8?q?=E7=BA=A0=E6=AD=A3=200078.=E5=AD=90?=
=?UTF-8?q?=E9=9B=86=E9=97=AE=E9=A2=98=20JS=20=E3=80=81TS=20=E7=89=88?=
=?UTF-8?q?=E6=9C=AC=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
JS 和 TS 里面 数组深拷贝一般采用 ES6 扩展运算符 ... ,或者 Array.from() 方法,而不会采用实例方法 slice. slice方法用于数组分割等操作,请注意代码书写规范!
---
problems/0078.子集.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/problems/0078.子集.md b/problems/0078.子集.md
index e1c52b5b..2b1c7643 100644
--- a/problems/0078.子集.md
+++ b/problems/0078.子集.md
@@ -260,7 +260,7 @@ var subsets = function(nums) {
let result = []
let path = []
function backtracking(startIndex) {
- result.push(path.slice())
+ result.push([...path])
for(let i = startIndex; i < nums.length; i++) {
path.push(nums[i])
backtracking(i + 1)
@@ -280,7 +280,7 @@ function subsets(nums: number[]): number[][] {
backTracking(nums, 0, []);
return resArr;
function backTracking(nums: number[], startIndex: number, route: number[]): void {
- resArr.push(route.slice());
+ resArr.push([...route]);
let length = nums.length;
if (startIndex === length) return;
for (let i = startIndex; i < length; i++) {
From 13ed28dbcf8eb40e94fafab3da7955e967f298bd Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Sat, 21 May 2022 10:10:36 +0800
Subject: [PATCH 138/162] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=200090.=E5=AD=90?=
=?UTF-8?q?=E9=9B=86II=20JS=E3=80=81TS=E7=89=88=E6=9C=AC=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
JS 和 TS 里面 数组深拷贝一般采用 ES6 扩展运算符 ... ,或者 Array.from() 方法,而不会采用实例方法 slice. slice方法用于数组分割等操作,请注意代码书写规范!
---
problems/0090.子集II.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md
index 74ce000b..dd64d199 100644
--- a/problems/0090.子集II.md
+++ b/problems/0090.子集II.md
@@ -299,7 +299,7 @@ var subsetsWithDup = function(nums) {
return a - b
})
function backtracing(startIndex, sortNums) {
- result.push(path.slice(0))
+ result.push([...path])
if(startIndex > nums.length - 1) {
return
}
@@ -327,7 +327,7 @@ function subsetsWithDup(nums: number[]): number[][] {
backTraking(nums, 0, []);
return resArr;
function backTraking(nums: number[], startIndex: number, route: number[]): void {
- resArr.push(route.slice());
+ resArr.push([...route]);
let length: number = nums.length;
if (startIndex === length) return;
for (let i = startIndex; i < length; i++) {
From 2da33bfc93326e3cdf5a358e5ef18646f97982fb Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Sat, 21 May 2022 10:46:39 +0800
Subject: [PATCH 139/162] =?UTF-8?q?=E7=BA=A0=E6=AD=A3=200046.=E5=85=A8?=
=?UTF-8?q?=E6=8E=92=E5=88=97=20TS=20=E7=89=88=E6=9C=AC=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
JS 和 TS 里面 数组深拷贝一般采用 ES6 扩展运算符 ... ,或者 Array.from() 方法,而不会采用实例方法 slice. slice方法用于数组分割等操作,请注意代码书写规范!
---
problems/0046.全排列.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md
index 836c3646..6c55e8ef 100644
--- a/problems/0046.全排列.md
+++ b/problems/0046.全排列.md
@@ -341,7 +341,7 @@ function permute(nums: number[]): number[][] {
return resArr;
function backTracking(nums: number[], route: number[]): void {
if (route.length === nums.length) {
- resArr.push(route.slice());
+ resArr.push([...route]);
return;
}
let tempVal: number;
From 38b10bcbfdb3f90f6af93a5b196ca0f68463d744 Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Sat, 21 May 2022 10:48:51 +0800
Subject: [PATCH 140/162] =?UTF-8?q?=E7=BA=A0=E6=AD=A3=200047.=E5=85=A8?=
=?UTF-8?q?=E6=8E=92=E5=88=97II=20JS=E3=80=81TS=20=E7=89=88=E6=9C=AC?=
=?UTF-8?q?=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
JS 和 TS 里面 数组深拷贝一般采用 ES6 扩展运算符 ... ,或者 Array.from() 方法,而不会采用实例方法 slice. slice方法用于数组分割等操作,请注意代码书写规范!
---
problems/0047.全排列II.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md
index cce25cd9..f635b8de 100644
--- a/problems/0047.全排列II.md
+++ b/problems/0047.全排列II.md
@@ -268,7 +268,7 @@ var permuteUnique = function (nums) {
function backtracing( used) {
if (path.length === nums.length) {
- result.push(path.slice())
+ result.push([...path])
return
}
for (let i = 0; i < nums.length; i++) {
@@ -303,7 +303,7 @@ function permuteUnique(nums: number[]): number[][] {
return resArr;
function backTracking(nums: number[], route: number[]): void {
if (route.length === nums.length) {
- resArr.push(route.slice());
+ resArr.push([...route]);
return;
}
for (let i = 0, length = nums.length; i < length; i++) {
From f36c1885cc8ccac0f38538b59b0a55e1b9f47913 Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Sat, 21 May 2022 11:01:21 +0800
Subject: [PATCH 141/162] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20=E5=9B=9E=E6=BA=AF?=
=?UTF-8?q?=E7=AE=97=E6=B3=95=E5=8E=BB=E9=87=8D=E9=97=AE=E9=A2=98=E7=9A=84?=
=?UTF-8?q?=E5=8F=A6=E4=B8=80=E7=A7=8D=E5=86=99=E6=B3=95=20JavaScript=20?=
=?UTF-8?q?=E7=89=88=E6=9C=AC=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/回溯算法去重问题的另一种写法.md | 84 +++++++++++++++++++++++-
1 file changed, 81 insertions(+), 3 deletions(-)
diff --git a/problems/回溯算法去重问题的另一种写法.md b/problems/回溯算法去重问题的另一种写法.md
index f48097e1..cbfe046a 100644
--- a/problems/回溯算法去重问题的另一种写法.md
+++ b/problems/回溯算法去重问题的另一种写法.md
@@ -365,6 +365,84 @@ class Solution:
return res
```
+JavaScript:
+
+**90.子集II**
+
+```javascript
+function subsetsWithDup(nums) {
+ nums.sort((a, b) => a - b);
+ const resArr = [];
+ backTraking(nums, 0, []);
+ return resArr;
+ function backTraking(nums, startIndex, route) {
+ resArr.push([...route]);
+ const helperSet = new Set();
+ for (let i = startIndex, length = nums.length; i < length; i++) {
+ if (helperSet.has(nums[i])) continue;
+ helperSet.add(nums[i]);
+ route.push(nums[i]);
+ backTraking(nums, i + 1, route);
+ route.pop();
+ }
+ }
+};
+```
+
+**40. 组合总和 II**
+
+```javascript
+function combinationSum2(candidates, target) {
+ candidates.sort((a, b) => a - b);
+ const resArr = [];
+ backTracking(candidates, target, 0, 0, []);
+ return resArr;
+ function backTracking( candidates, target, curSum, startIndex, route ) {
+ if (curSum > target) return;
+ if (curSum === target) {
+ resArr.push([...route]);
+ return;
+ }
+ const helperSet = new Set();
+ for (let i = startIndex, length = candidates.length; i < length; i++) {
+ let tempVal = candidates[i];
+ if (helperSet.has(tempVal)) continue;
+ helperSet.add(tempVal);
+ route.push(tempVal);
+ backTracking(candidates, target, curSum + tempVal, i + 1, route);
+ route.pop();
+ }
+ }
+};
+```
+
+**47. 全排列 II**
+
+```javaescript
+function permuteUnique(nums) {
+ const resArr = [];
+ const usedArr = [];
+ backTracking(nums, []);
+ return resArr;
+ function backTracking(nums, route) {
+ if (nums.length === route.length) {
+ resArr.push([...route]);
+ return;
+ }
+ const usedSet = new Set();
+ for (let i = 0, length = nums.length; i < length; i++) {
+ if (usedArr[i] === true || usedSet.has(nums[i])) continue;
+ usedSet.add(nums[i]);
+ route.push(nums[i]);
+ usedArr[i] = true;
+ backTracking(nums, route);
+ usedArr[i] = false;
+ route.pop();
+ }
+ }
+};
+```
+
TypeScript:
**90.子集II**
@@ -376,7 +454,7 @@ function subsetsWithDup(nums: number[]): number[][] {
backTraking(nums, 0, []);
return resArr;
function backTraking(nums: number[], startIndex: number, route: number[]): void {
- resArr.push(route.slice());
+ resArr.push([...route]);
const helperSet: Set = new Set();
for (let i = startIndex, length = nums.length; i < length; i++) {
if (helperSet.has(nums[i])) continue;
@@ -403,7 +481,7 @@ function combinationSum2(candidates: number[], target: number): number[][] {
) {
if (curSum > target) return;
if (curSum === target) {
- resArr.push(route.slice());
+ resArr.push([...route]);
return;
}
const helperSet: Set = new Set();
@@ -430,7 +508,7 @@ function permuteUnique(nums: number[]): number[][] {
return resArr;
function backTracking(nums: number[], route: number[]): void {
if (nums.length === route.length) {
- resArr.push(route.slice());
+ resArr.push([...route]);
return;
}
const usedSet: Set = new Set();
From f6501464cfdfe0c207e5f1026b1b3251d9b5c927 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sat, 21 May 2022 11:48:18 +0800
Subject: [PATCH 142/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880647.?=
=?UTF-8?q?=E5=9B=9E=E6=96=87=E5=AD=90=E4=B8=B2.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0647.回文子串.md | 57 +++++++++++++++++++++++++++++++++++++++
1 file changed, 57 insertions(+)
diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md
index 913aec65..6045ba7b 100644
--- a/problems/0647.回文子串.md
+++ b/problems/0647.回文子串.md
@@ -406,6 +406,63 @@ const countSubstrings = (s) => {
}
```
+TypeScript:
+
+> 动态规划:
+
+```typescript
+function countSubstrings(s: string): number {
+ /**
+ dp[i][j]: [i,j]区间内的字符串是否为回文(左闭右闭)
+ */
+ const length: number = s.length;
+ const dp: boolean[][] = new Array(length).fill(0)
+ .map(_ => new Array(length).fill(false));
+ let resCount: number = 0;
+ // 自下而上,自左向右遍历
+ for (let i = length - 1; i >= 0; i--) {
+ for (let j = i; j < length; j++) {
+ if (
+ s[i] === s[j] &&
+ (j - i <= 1 || dp[i + 1][j - 1] === true)
+ ) {
+ dp[i][j] = true;
+ resCount++;
+ }
+ }
+ }
+ return resCount;
+};
+```
+
+> 双指针法:
+
+```typescript
+function countSubstrings(s: string): number {
+ const length: number = s.length;
+ let resCount: number = 0;
+ for (let i = 0; i < length; i++) {
+ resCount += expandRange(s, i, i);
+ resCount += expandRange(s, i, i + 1);
+ }
+ return resCount;
+};
+function expandRange(s: string, left: number, right: number): number {
+ let palindromeNum: number = 0;
+ while (
+ left >= 0 && right < s.length &&
+ s[left] === s[right]
+ ) {
+ palindromeNum++;
+ left--;
+ right++;
+ }
+ return palindromeNum;
+}
+```
+
+
+
-----------------------
From 8e7663c9c663db8c7d24aa1528d45c68fe6f5e29 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sat, 21 May 2022 14:26:24 +0800
Subject: [PATCH 143/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880516.?=
=?UTF-8?q?=E6=9C=80=E9=95=BF=E5=9B=9E=E6=96=87=E5=AD=90=E5=BA=8F=E5=88=97?=
=?UTF-8?q?.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0516.最长回文子序列.md | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/problems/0516.最长回文子序列.md b/problems/0516.最长回文子序列.md
index 69536cef..1b0ee9a3 100644
--- a/problems/0516.最长回文子序列.md
+++ b/problems/0516.最长回文子序列.md
@@ -236,6 +236,35 @@ const longestPalindromeSubseq = (s) => {
};
```
+TypeScript:
+
+```typescript
+function longestPalindromeSubseq(s: string): number {
+ /**
+ dp[i][j]:[i,j]区间内,最长回文子序列的长度
+ */
+ const length: number = s.length;
+ const dp: number[][] = new Array(length).fill(0)
+ .map(_ => new Array(length).fill(0));
+ for (let i = 0; i < length; i++) {
+ dp[i][i] = 1;
+ }
+ // 自下而上,自左往右遍历
+ for (let i = length - 1; i >= 0; i--) {
+ for (let j = i + 1; j < length; j++) {
+ if (s[i] === s[j]) {
+ dp[i][j] = dp[i + 1][j - 1] + 2;
+ } else {
+ dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]);
+ }
+ }
+ }
+ return dp[0][length - 1];
+};
+```
+
+
+
-----------------------
From f39d349d308a4657c7cbe247060c1fcec7272497 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sat, 21 May 2022 16:19:25 +0800
Subject: [PATCH 144/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880739.?=
=?UTF-8?q?=E6=AF=8F=E6=97=A5=E6=B8=A9=E5=BA=A6.md=EF=BC=89=EF=BC=9A?=
=?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0739.每日温度.md | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md
index 58edd489..5e7a52ac 100644
--- a/problems/0739.每日温度.md
+++ b/problems/0739.每日温度.md
@@ -371,6 +371,32 @@ var dailyTemperatures = function(temperatures) {
};
```
+TypeScript:
+
+> 精简版:
+
+```typescript
+function dailyTemperatures(temperatures: number[]): number[] {
+ const length: number = temperatures.length;
+ const stack: number[] = [];
+ const resArr: number[] = new Array(length).fill(0);
+ stack.push(0);
+ for (let i = 1; i < length; i++) {
+ let top = stack[stack.length - 1];
+ while (
+ stack.length > 0 &&
+ temperatures[top] < temperatures[i]
+ ) {
+ resArr[top] = i - top;
+ stack.pop();
+ top = stack[stack.length - 1];
+ }
+ stack.push(i);
+ }
+ return resArr;
+};
+```
+
From ef9cefe08939725adadbefd5e49c79d7ce9e9b63 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Sat, 21 May 2022 17:11:25 +0800
Subject: [PATCH 145/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200104.=E4=BA=8C?=
=?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6?=
=?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0104.二叉树的最大深度.md | 99 +++++++++++++++++++++++++++++--
1 file changed, 93 insertions(+), 6 deletions(-)
diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md
index 2229a854..40c65af9 100644
--- a/problems/0104.二叉树的最大深度.md
+++ b/problems/0104.二叉树的最大深度.md
@@ -468,7 +468,7 @@ class solution:
## go
-
+### 104.二叉树的最大深度
```go
/**
* definition for a binary tree node.
@@ -521,6 +521,8 @@ func maxdepth(root *treenode) int {
## javascript
+### 104.二叉树的最大深度
+
```javascript
var maxdepth = function(root) {
if (root === null) return 0;
@@ -568,6 +570,8 @@ var maxDepth = function(root) {
};
```
+### 559.n叉树的最大深度
+
N叉树的最大深度 递归写法
```js
var maxDepth = function(root) {
@@ -600,9 +604,9 @@ var maxDepth = function(root) {
};
```
-## TypeScript:
+## TypeScript
-> 二叉树的最大深度:
+### 104.二叉树的最大深度
```typescript
// 后续遍历(自下而上)
@@ -645,7 +649,7 @@ function maxDepth(root: TreeNode | null): number {
};
```
-> N叉树的最大深度
+### 559.n叉树的最大深度
```typescript
// 后续遍历(自下而上)
@@ -675,6 +679,8 @@ function maxDepth(root: TreeNode | null): number {
## C
+### 104.二叉树的最大深度
+
二叉树最大深度递归
```c
int maxDepth(struct TreeNode* root){
@@ -731,7 +737,8 @@ int maxDepth(struct TreeNode* root){
## Swift
->二叉树最大深度
+### 104.二叉树的最大深度
+
```swift
// 递归 - 后序
func maxDepth1(_ root: TreeNode?) -> Int {
@@ -770,7 +777,8 @@ func maxDepth(_ root: TreeNode?) -> Int {
}
```
->N叉树最大深度
+### 559.n叉树的最大深度
+
```swift
// 递归
func maxDepth(_ root: Node?) -> Int {
@@ -806,5 +814,84 @@ func maxDepth1(_ root: Node?) -> Int {
}
```
+## Scala
+
+### 104.二叉树的最大深度
+递归法:
+```scala
+object Solution {
+ def maxDepth(root: TreeNode): Int = {
+ def process(curNode: TreeNode): Int = {
+ if (curNode == null) return 0
+ // 递归左节点和右节点,返回最大的,最后+1
+ math.max(process(curNode.left), process(curNode.right)) + 1
+ }
+ // 调用递归方法,return关键字可以省略
+ process(root)
+ }
+}
+```
+
+迭代法:
+```scala
+object Solution {
+ import scala.collection.mutable
+ def maxDepth(root: TreeNode): Int = {
+ var depth = 0
+ if (root == null) return depth
+ val queue = mutable.Queue[TreeNode]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ val len = queue.size
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ depth += 1 // 只要有层次就+=1
+ }
+ depth
+ }
+}
+```
+
+### 559.n叉树的最大深度
+
+递归法:
+```scala
+object Solution {
+ def maxDepth(root: Node): Int = {
+ if (root == null) return 0
+ var depth = 0
+ for (node <- root.children) {
+ depth = math.max(depth, maxDepth(node))
+ }
+ depth + 1
+ }
+}
+```
+
+迭代法: (层序遍历)
+```scala
+object Solution {
+ import scala.collection.mutable
+ def maxDepth(root: Node): Int = {
+ if (root == null) return 0
+ var depth = 0
+ val queue = mutable.Queue[Node]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ val len = queue.size
+ depth += 1
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ for (node <- curNode.children) queue.enqueue(node)
+ }
+ }
+ depth
+ }
+}
+```
+
-----------------------
From 3a7afacdeb785d271dbd57c236c2bd344a88b343 Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Sat, 21 May 2022 17:18:02 +0800
Subject: [PATCH 146/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200111.=E4=BA=8C?=
=?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6?=
=?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0111.二叉树的最小深度.md | 39 +++++++++++++++++++++++++++++++
1 file changed, 39 insertions(+)
diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md
index 224caa5e..a7eb913e 100644
--- a/problems/0111.二叉树的最小深度.md
+++ b/problems/0111.二叉树的最小深度.md
@@ -488,5 +488,44 @@ func minDepth(_ root: TreeNode?) -> Int {
}
```
+## Scala
+
+递归法:
+```scala
+object Solution {
+ def minDepth(root: TreeNode): Int = {
+ if (root == null) return 0
+ if (root.left == null && root.right != null) return 1 + minDepth(root.right)
+ if (root.left != null && root.right == null) return 1 + minDepth(root.left)
+ // 如果两侧都不为空,则取最小值,return关键字可以省略
+ 1 + math.min(minDepth(root.left), minDepth(root.right))
+ }
+}
+```
+
+迭代法:
+```scala
+object Solution {
+ import scala.collection.mutable
+ def minDepth(root: TreeNode): Int = {
+ if (root == null) return 0
+ var depth = 0
+ val queue = mutable.Queue[TreeNode]()
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ depth += 1
+ val len = queue.size
+ for (i <- 0 until len) {
+ val curNode = queue.dequeue()
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ if (curNode.left == null && curNode.right == null) return depth
+ }
+ }
+ depth
+ }
+}
+```
+
-----------------------
From 9cbd053e0500846fccac3936aeb497a75906133e Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sat, 21 May 2022 19:49:59 +0800
Subject: [PATCH 147/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880496.?=
=?UTF-8?q?=E4=B8=8B=E4=B8=80=E4=B8=AA=E6=9B=B4=E5=A4=A7=E5=85=83=E7=B4=A0?=
=?UTF-8?q?I.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0496.下一个更大元素I.md | 31 +++++++++++++++++++++++++++++++
1 file changed, 31 insertions(+)
diff --git a/problems/0496.下一个更大元素I.md b/problems/0496.下一个更大元素I.md
index 02339677..274cc32b 100644
--- a/problems/0496.下一个更大元素I.md
+++ b/problems/0496.下一个更大元素I.md
@@ -332,5 +332,36 @@ var nextGreaterElement = function (nums1, nums2) {
};
```
+TypeScript:
+
+```typescript
+function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
+ const resArr: number[] = new Array(nums1.length).fill(-1);
+ const stack: number[] = [];
+ const helperMap: Map = new Map();
+ nums1.forEach((num, index) => {
+ helperMap.set(num, index);
+ })
+ stack.push(0);
+ for (let i = 1, length = nums2.length; i < length; i++) {
+ let top = stack[stack.length - 1];
+ while (stack.length > 0 && nums2[top] < nums2[i]) {
+ let index = helperMap.get(nums2[top]);
+ if (index !== undefined) {
+ resArr[index] = nums2[i];
+ }
+ stack.pop();
+ top = stack[stack.length - 1];
+ }
+ if (helperMap.get(nums2[i]) !== undefined) {
+ stack.push(i);
+ }
+ }
+ return resArr;
+};
+```
+
+
+
-----------------------
From 10ad5411d98765272a4119ecf97b6d72c8e85ada Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sat, 21 May 2022 20:37:58 +0800
Subject: [PATCH 148/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880503.?=
=?UTF-8?q?=E4=B8=8B=E4=B8=80=E4=B8=AA=E6=9B=B4=E5=A4=A7=E5=85=83=E7=B4=A0?=
=?UTF-8?q?II.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0503.下一个更大元素II.md | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md
index ace4d40b..33807d26 100644
--- a/problems/0503.下一个更大元素II.md
+++ b/problems/0503.下一个更大元素II.md
@@ -182,5 +182,31 @@ var nextGreaterElements = function (nums) {
return res;
};
```
+TypeScript:
+
+```typescript
+function nextGreaterElements(nums: number[]): number[] {
+ const length: number = nums.length;
+ const stack: number[] = [];
+ stack.push(0);
+ const resArr: number[] = new Array(length).fill(-1);
+ for (let i = 1; i < length * 2; i++) {
+ const index = i % length;
+ let top = stack[stack.length - 1];
+ while (stack.length > 0 && nums[top] < nums[index]) {
+ resArr[top] = nums[index];
+ stack.pop();
+ top = stack[stack.length - 1];
+ }
+ if (i < length) {
+ stack.push(i);
+ }
+ }
+ return resArr;
+};
+```
+
+
+
-----------------------
From 3de2992235e43b6ce40a35624a42a08b5a5a866b Mon Sep 17 00:00:00 2001
From: xuxiaomeng <961592690@qq.com>
Date: Sat, 21 May 2022 21:02:59 +0800
Subject: [PATCH 149/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A00027.=E7=A7=BB?=
=?UTF-8?q?=E9=99=A4=E5=85=83=E7=B4=A0=20Kotlin=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0027.移除元素.md | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md
index 590cf0b9..f0cb5375 100644
--- a/problems/0027.移除元素.md
+++ b/problems/0027.移除元素.md
@@ -329,5 +329,16 @@ int removeElement(int* nums, int numsSize, int val){
}
```
+Kotlin:
+```kotlin
+fun removeElement(nums: IntArray, `val`: Int): Int {
+ var slowIndex = 0 // 初始化慢指针
+ for (fastIndex in nums.indices) {
+ if (nums[fastIndex] != `val`) nums[slowIndex++] = nums[fastIndex] // 在慢指针所在位置存储未被删除的元素
+ }
+ return slowIndex
+ }
+```
+
-----------------------
From 97211892492753b1903a882c68b4387051b652cb Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sun, 22 May 2022 00:12:15 +0800
Subject: [PATCH 150/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880042.?=
=?UTF-8?q?=E6=8E=A5=E9=9B=A8=E6=B0=B4.md=EF=BC=89=EF=BC=9A=E5=A2=9E?=
=?UTF-8?q?=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0042.接雨水.md | 85 +++++++++++++++++++++++++++++++++++++++++
1 file changed, 85 insertions(+)
diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md
index b232ce22..060c0b45 100644
--- a/problems/0042.接雨水.md
+++ b/problems/0042.接雨水.md
@@ -744,6 +744,91 @@ var trap = function(height) {
};
```
+### TypeScript
+
+双指针法:
+
+```typescript
+function trap(height: number[]): number {
+ const length: number = height.length;
+ let resVal: number = 0;
+ for (let i = 0; i < length; i++) {
+ let leftMaxHeight: number = height[i],
+ rightMaxHeight: number = height[i];
+ let leftIndex: number = i - 1,
+ rightIndex: number = i + 1;
+ while (leftIndex >= 0) {
+ if (height[leftIndex] > leftMaxHeight)
+ leftMaxHeight = height[leftIndex];
+ leftIndex--;
+ }
+ while (rightIndex < length) {
+ if (height[rightIndex] > rightMaxHeight)
+ rightMaxHeight = height[rightIndex];
+ rightIndex++;
+ }
+ resVal += Math.min(leftMaxHeight, rightMaxHeight) - height[i];
+ }
+ return resVal;
+};
+```
+
+动态规划:
+
+```typescript
+function trap(height: number[]): number {
+ const length: number = height.length;
+ const leftMaxHeightDp: number[] = [],
+ rightMaxHeightDp: number[] = [];
+ leftMaxHeightDp[0] = height[0];
+ rightMaxHeightDp[length - 1] = height[length - 1];
+ for (let i = 1; i < length; i++) {
+ leftMaxHeightDp[i] = Math.max(height[i], leftMaxHeightDp[i - 1]);
+ }
+ for (let i = length - 2; i >= 0; i--) {
+ rightMaxHeightDp[i] = Math.max(height[i], rightMaxHeightDp[i + 1]);
+ }
+ let resVal: number = 0;
+ for (let i = 0; i < length; i++) {
+ resVal += Math.min(leftMaxHeightDp[i], rightMaxHeightDp[i]) - height[i];
+ }
+ return resVal;
+};
+```
+
+单调栈:
+
+```typescript
+function trap(height: number[]): number {
+ const length: number = height.length;
+ const stack: number[] = [];
+ stack.push(0);
+ let resVal: number = 0;
+ for (let i = 1; i < length; i++) {
+ let top = stack[stack.length - 1];
+ if (height[top] > height[i]) {
+ stack.push(i);
+ } else if (height[top] === height[i]) {
+ stack.pop();
+ stack.push(i);
+ } else {
+ while (stack.length > 0 && height[top] < height[i]) {
+ let mid = stack.pop();
+ if (stack.length > 0) {
+ let left = stack[stack.length - 1];
+ let h = Math.min(height[left], height[i]) - height[mid];
+ let w = i - left - 1;
+ resVal += h * w;
+ top = stack[stack.length - 1];
+ }
+ }
+ stack.push(i);
+ }
+ }
+ return resVal;
+};
+```
+
### C:
一种更简便的双指针方法:
From 278011c2df448c295985c0ba4f2ddc0843f4efd7 Mon Sep 17 00:00:00 2001
From: programmercarl <826123027@qq.com>
Date: Sun, 22 May 2022 11:11:50 +0800
Subject: [PATCH 151/162] Update
---
problems/0056.合并区间.md | 4 +--
problems/0077.组合.md | 25 +++++++--------
problems/0101.对称二叉树.md | 4 +--
problems/0435.无重叠区间.md | 2 +-
problems/0452.用最少数量的箭引爆气球.md | 4 +--
problems/面试题 02.07. 解法更新.md | 41 -------------------------
6 files changed, 20 insertions(+), 60 deletions(-)
delete mode 100644 problems/面试题 02.07. 解法更新.md
diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md
index a9caeaf0..0d002b46 100644
--- a/problems/0056.合并区间.md
+++ b/problems/0056.合并区间.md
@@ -112,8 +112,8 @@ public:
};
```
-* 时间复杂度:$O(n\log n)$ ,有一个快排
-* 空间复杂度:$O(1)$,我没有算result数组(返回值所需容器占的空间)
+* 时间复杂度:O(nlog n) ,有一个快排
+* 空间复杂度:O(n),有一个快排,最差情况(倒序)时,需要n次递归调用。因此确实需要O(n)的栈空间
## 总结
diff --git a/problems/0077.组合.md b/problems/0077.组合.md
index 4560c5b7..9e0398ab 100644
--- a/problems/0077.组合.md
+++ b/problems/0077.组合.md
@@ -27,7 +27,7 @@
也可以直接看我的B站视频:[带你学透回溯算法-组合问题(对应力扣题目:77.组合)](https://www.bilibili.com/video/BV1ti4y1L7cv#reply3733925949)
-# 思路
+## 思路
本题这是回溯法的经典题目。
@@ -232,7 +232,7 @@ void backtracking(参数) {
**对比一下本题的代码,是不是发现有点像!** 所以有了这个模板,就有解题的大体方向,不至于毫无头绪。
-# 总结
+## 总结
组合问题是回溯法解决的经典问题,我们开始的时候给大家列举一个很形象的例子,就是n为100,k为50的话,直接想法就需要50层for循环。
@@ -242,7 +242,7 @@ void backtracking(参数) {
接着用回溯法三部曲,逐步分析了函数参数、终止条件和单层搜索的过程。
-# 剪枝优化
+## 剪枝优化
我们说过,回溯法虽然是暴力搜索,但也有时候可以有点剪枝优化一下的。
@@ -324,7 +324,7 @@ public:
};
```
-# 剪枝总结
+## 剪枝总结
本篇我们准对求组合问题的回溯法代码做了剪枝优化,这个优化如果不画图的话,其实不好理解,也不好讲清楚。
@@ -334,10 +334,10 @@ public:
-# 其他语言版本
+## 其他语言版本
-## Java:
+### Java:
```java
class Solution {
List> result = new ArrayList<>();
@@ -366,6 +366,8 @@ class Solution {
}
```
+### Python
+
Python2:
```python
class Solution(object):
@@ -395,7 +397,6 @@ class Solution(object):
return result
```
-## Python
```python
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
@@ -432,7 +433,7 @@ class Solution:
```
-## javascript
+### javascript
剪枝:
```javascript
@@ -456,7 +457,7 @@ const combineHelper = (n, k, startIndex) => {
}
```
-## TypeScript
+### TypeScript
```typescript
function combine(n: number, k: number): number[][] {
@@ -479,7 +480,7 @@ function combine(n: number, k: number): number[][] {
-## Go
+### Go
```Go
var res [][]int
func combine(n int, k int) [][]int {
@@ -534,7 +535,7 @@ func backtrack(n,k,start int,track []int){
}
```
-## C
+### C
```c
int* path;
int pathTop;
@@ -642,7 +643,7 @@ int** combine(int n, int k, int* returnSize, int** returnColumnSizes){
}
```
-## Swift
+### Swift
```swift
func combine(_ n: Int, _ k: Int) -> [[Int]] {
diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md
index e4e232c8..1eb43589 100644
--- a/problems/0101.对称二叉树.md
+++ b/problems/0101.对称二叉树.md
@@ -238,7 +238,7 @@ public:
};
```
-# 总结
+## 总结
这次我们又深度剖析了一道二叉树的“简单题”,大家会发现,真正的把题目搞清楚其实并不简单,leetcode上accept了和真正掌握了还是有距离的。
@@ -248,7 +248,7 @@ public:
如果已经做过这道题目的同学,读完文章可以再去看看这道题目,思考一下,会有不一样的发现!
-# 相关题目推荐
+## 相关题目推荐
这两道题目基本和本题是一样的,只要稍加修改就可以AC。
diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md
index b24ca024..32790a34 100644
--- a/problems/0435.无重叠区间.md
+++ b/problems/0435.无重叠区间.md
@@ -93,7 +93,7 @@ public:
};
```
* 时间复杂度:O(nlog n) ,有一个快排
-* 空间复杂度:O(1)
+* 空间复杂度:O(n),有一个快排,最差情况(倒序)时,需要n次递归调用。因此确实需要O(n)的栈空间
大家此时会发现如此复杂的一个问题,代码实现却这么简单!
diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md
index 33bbad55..327694ca 100644
--- a/problems/0452.用最少数量的箭引爆气球.md
+++ b/problems/0452.用最少数量的箭引爆气球.md
@@ -105,8 +105,8 @@ public:
};
```
-* 时间复杂度:$O(n\log n)$,因为有一个快排
-* 空间复杂度:$O(1)$
+* 时间复杂度:O(nlog n),因为有一个快排
+* 空间复杂度:O(1),有一个快排,最差情况(倒序)时,需要n次递归调用。因此确实需要O(n)的栈空间
可以看出代码并不复杂。
diff --git a/problems/面试题 02.07. 解法更新.md b/problems/面试题 02.07. 解法更新.md
deleted file mode 100644
index 6115d02e..00000000
--- a/problems/面试题 02.07. 解法更新.md
+++ /dev/null
@@ -1,41 +0,0 @@
-# 双指针,不计算链表长度
-设置指向headA和headB的指针pa、pb,分别遍历两个链表,每次循环同时更新pa和pb。
-* 当链表A遍历完之后,即pa为空时,将pa指向headB;
-* 当链表B遍历完之后,即pa为空时,将pb指向headA;
-* 当pa与pb相等时,即指向同一个节点,该节点即为相交起始节点。
-* 若链表不相交,则pa、pb同时为空时退出循环,即如果链表不相交,pa与pb在遍历过全部节点后同时指向结尾空节点,此时退出循环,返回空。
-# 证明思路
-设链表A不相交部分长度为a,链表B不相交部分长度为b,两个链表相交部分长度为c。
-在pa指向链表A时,即pa为空之前,pa经过链表A不相交部分和相交部分,走过的长度为a+c;
-pa指向链表B后,在移动相交节点之前经过链表B不相交部分,走过的长度为b,总合为a+c+b。
-同理,pb走过长度的总合为b+c+a。二者相等,即pa与pb可同时到达相交起始节点。
-该方法可避免计算具体链表长度。
-```cpp
-class Solution {
-public:
- ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
- //链表为空时,返回空指针
- if(headA == nullptr || headB == nullptr) return nullptr;
- ListNode* pa = headA;
- ListNode* pb = headB;
- //pa与pb在遍历过全部节点后,同时指向结尾空节点时退出循环
- while(pa != nullptr || pb != nullptr){
- //pa为空时,将pa指向headB
- if(pa == nullptr){
- pa = headB;
- }
- //pa为空时,将pb指向headA
- if(pb == nullptr){
- pb = headA;
- }
- //pa与pb相等时,返回相交起始节点
- if(pa == pb){
- return pa;
- }
- pa = pa->next;
- pb = pb->next;
- }
- return nullptr;
- }
-};
-```
From b06b83867b466fa2d72268c0a6ef50e4da52aac3 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Sun, 22 May 2022 17:09:55 +0800
Subject: [PATCH 152/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880084.?=
=?UTF-8?q?=E6=9F=B1=E7=8A=B6=E5=9B=BE=E4=B8=AD=E6=9C=80=E5=A4=A7=E7=9A=84?=
=?UTF-8?q?=E7=9F=A9=E5=BD=A2.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?=
=?UTF-8?q?ript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0084.柱状图中最大的矩形.md | 90 +++++++++++++++++++++++++++++
1 file changed, 90 insertions(+)
diff --git a/problems/0084.柱状图中最大的矩形.md b/problems/0084.柱状图中最大的矩形.md
index 439a3bc5..8f10a582 100644
--- a/problems/0084.柱状图中最大的矩形.md
+++ b/problems/0084.柱状图中最大的矩形.md
@@ -486,5 +486,95 @@ var largestRectangleArea = function(heights) {
return maxArea;
};
```
+TypeScript:
+
+> 双指针法(会超时):
+
+```typescript
+function largestRectangleArea(heights: number[]): number {
+ let resMax: number = 0;
+ for (let i = 0, length = heights.length; i < length; i++) {
+ // 左开右开
+ let left: number = i - 1,
+ right: number = i + 1;
+ while (left >= 0 && heights[left] >= heights[i]) {
+ left--;
+ }
+ while (right < length && heights[right] >= heights[i]) {
+ right++;
+ }
+ resMax = Math.max(resMax, heights[i] * (right - left - 1));
+ }
+ return resMax;
+};
+```
+
+> 动态规划预处理:
+
+```typescript
+function largestRectangleArea(heights: number[]): number {
+ const length: number = heights.length;
+ const leftHeightDp: number[] = [],
+ rightHeightDp: number[] = [];
+ leftHeightDp[0] = -1;
+ rightHeightDp[length - 1] = length;
+ for (let i = 1; i < length; i++) {
+ let j = i - 1;
+ while (j >= 0 && heights[i] <= heights[j]) {
+ j = leftHeightDp[j];
+ }
+ leftHeightDp[i] = j;
+ }
+ for (let i = length - 2; i >= 0; i--) {
+ let j = i + 1;
+ while (j < length && heights[i] <= heights[j]) {
+ j = rightHeightDp[j];
+ }
+ rightHeightDp[i] = j;
+ }
+ let resMax: number = 0;
+ for (let i = 0; i < length; i++) {
+ let area = heights[i] * (rightHeightDp[i] - leftHeightDp[i] - 1);
+ resMax = Math.max(resMax, area);
+ }
+ return resMax;
+};
+```
+
+> 单调栈:
+
+```typescript
+function largestRectangleArea(heights: number[]): number {
+ heights.push(0);
+ const length: number = heights.length;
+ // 栈底->栈顶:严格单调递增
+ const stack: number[] = [];
+ stack.push(0);
+ let resMax: number = 0;
+ for (let i = 1; i < length; i++) {
+ let top = stack[stack.length - 1];
+ if (heights[top] < heights[i]) {
+ stack.push(i);
+ } else if (heights[top] === heights[i]) {
+ stack.pop();
+ stack.push(i);
+ } else {
+ while (stack.length > 0 && heights[top] > heights[i]) {
+ let mid = stack.pop();
+ let left = stack.length > 0 ? stack[stack.length - 1] : -1;
+ let w = i - left - 1;
+ let h = heights[mid];
+ resMax = Math.max(resMax, w * h);
+ top = stack[stack.length - 1];
+ }
+ stack.push(i);
+ }
+ }
+ return resMax;
+};
+```
+
+
+
-----------------------
From 10b440ec27b814715dad23110b919c33d59403b6 Mon Sep 17 00:00:00 2001
From: xuxiaomeng <961592690@qq.com>
Date: Mon, 23 May 2022 09:38:24 +0800
Subject: [PATCH 153/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A00977.=E6=9C=89?=
=?UTF-8?q?=E5=BA=8F=E6=95=B0=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9=20Kotlin?=
=?UTF-8?q?=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0977.有序数组的平方.md | 23 ++++++++++++++++++++++-
1 file changed, 22 insertions(+), 1 deletion(-)
diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md
index 24276bcf..9c06d8a3 100644
--- a/problems/0977.有序数组的平方.md
+++ b/problems/0977.有序数组的平方.md
@@ -359,7 +359,28 @@ class Solution {
}
```
-
+Kotlin:
+```kotlin
+class Solution {
+ // 双指针法
+ fun sortedSquares(nums: IntArray): IntArray {
+ var res = IntArray(nums.size)
+ var left = 0 // 指向数组的最左端
+ var right = nums.size - 1 // 指向数组端最右端
+ // 选择平方数更大的那一个往 res 数组中倒序填充
+ for (index in nums.size - 1 downTo 0) {
+ if (nums[left] * nums[left] > nums[right] * nums[right]) {
+ res[index] = nums[left] * nums[left]
+ left++
+ } else {
+ res[index] = nums[right] * nums[right]
+ right--
+ }
+ }
+ return res
+ }
+}
+```
-----------------------
From 530422fa3ecf004d27f45552e909506947992902 Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Mon, 23 May 2022 10:04:15 +0800
Subject: [PATCH 154/162] =?UTF-8?q?0416.=E5=88=86=E5=89=B2=E7=AD=89?=
=?UTF-8?q?=E5=92=8C=E5=AD=90=E9=9B=86=20=E6=96=B0=E5=A2=9E=20typescript?=
=?UTF-8?q?=20=E8=A7=A3=E6=B3=95=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0416.分割等和子集.md | 17 +++++++++++++++++
1 file changed, 17 insertions(+)
diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md
index 6e93ae8e..01ea825e 100644
--- a/problems/0416.分割等和子集.md
+++ b/problems/0416.分割等和子集.md
@@ -416,7 +416,24 @@ var canPartition = function(nums) {
};
```
+TypeScript:
+```ts
+function canPartition(nums: number[]): boolean {
+ const sum: number = nums.reduce((a: number, b: number): number => a + b);
+ if (sum % 2 === 1) return false;
+ const target: number = sum / 2;
+ // dp[j]表示容量(总数和)为j的背包所能装下的数(下标[0, i]之间任意取)的总和(<= 容量)的最大值
+ const dp: number[] = new Array(target + 1).fill(0);
+ const n: number = nums.length;
+ for (let i: number = 0; i < n; i++) {
+ for (let j: number = target; j >= nums[i]; j--) {
+ dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]);
+ }
+ }
+ return dp[target] === target;
+};
+```
-----------------------
From 8f9c8e5fb1f9d89830b92a06f1fc59d97fd84772 Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Mon, 23 May 2022 10:10:48 +0800
Subject: [PATCH 155/162] =?UTF-8?q?1049.=E6=9C=80=E5=90=8E=E4=B8=80?=
=?UTF-8?q?=E5=9D=97=E7=9F=B3=E5=A4=B4=E9=87=8D=E9=87=8F=20=E6=96=B0?=
=?UTF-8?q?=E5=A2=9Etypescript=E7=89=88=E6=9C=AC=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/1049.最后一块石头的重量II.md | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md
index ee0ddef2..8d3eeb3b 100644
--- a/problems/1049.最后一块石头的重量II.md
+++ b/problems/1049.最后一块石头的重量II.md
@@ -277,5 +277,23 @@ var lastStoneWeightII = function (stones) {
};
```
+TypeScript版本
+
+```ts
+function lastStoneWeightII(stones: number[]): number {
+ const sum: number = stones.reduce((a: number, b:number): number => a + b);
+ const target: number = Math.floor(sum / 2);
+ const n: number = stones.length;
+ // dp[j]表示容量(总数和)为j的背包所能装下的数(下标[0, i]之间任意取)的总和(<= 容量)的最大值
+ const dp: number[] = new Array(target + 1).fill(0);
+ for (let i: number = 0; i < n; i++ ) {
+ for (let j: number = target; j >= stones[i]; j--) {
+ dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
+ }
+ }
+ return sum - dp[target] - dp[target];
+};
+```
+
-----------------------
From ffc91f1f1ca6099af747c77c5cdbfc21125fc140 Mon Sep 17 00:00:00 2001
From: Luo <82520819+Jerry-306@users.noreply.github.com>
Date: Mon, 23 May 2022 10:20:08 +0800
Subject: [PATCH 156/162] =?UTF-8?q?0494.=E7=9B=AE=E6=A0=87=E5=92=8C=20?=
=?UTF-8?q?=E6=96=B0=E5=A2=9Etypescript=E7=89=88=E6=9C=AC=E4=BB=A3?=
=?UTF-8?q?=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0494.目标和.md | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md
index 99b76834..929b97d4 100644
--- a/problems/0494.目标和.md
+++ b/problems/0494.目标和.md
@@ -351,6 +351,28 @@ const findTargetSumWays = (nums, target) => {
};
```
+TypeScript:
+
+```ts
+function findTargetSumWays(nums: number[], target: number): number {
+ // 把数组分成两个组合left, right.left + right = sum, left - right = target.
+ const sum: number = nums.reduce((a: number, b: number): number => a + b);
+ if ((sum + target) % 2 || Math.abs(target) > sum) return 0;
+ const left: number = (sum + target) / 2;
+
+ // 将问题转化为装满容量为left的背包有多少种方法
+ // dp[i]表示装满容量为i的背包有多少种方法
+ const dp: number[] = new Array(left + 1).fill(0);
+ dp[0] = 1; // 装满容量为0的背包有1种方法(什么也不装)
+ for (let i: number = 0; i < nums.length; i++) {
+ for (let j: number = left; j >= nums[i]; j--) {
+ dp[j] += dp[j - nums[i]];
+ }
+ }
+ return dp[left];
+};
+```
+
-----------------------
From 282cdc2b44b755098d223d0f9c8bd36bf0e85959 Mon Sep 17 00:00:00 2001
From: Steve2020 <841532108@qq.com>
Date: Mon, 23 May 2022 11:18:04 +0800
Subject: [PATCH 157/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=881365.?=
=?UTF-8?q?=E6=9C=89=E5=A4=9A=E5=B0=91=E5=B0=8F=E4=BA=8E=E5=BD=93=E5=89=8D?=
=?UTF-8?q?=E6=95=B0=E5=AD=97=E7=9A=84=E6=95=B0=E5=AD=97.md=EF=BC=89?=
=?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/1365.有多少小于当前数字的数字.md | 40 +++++++++++++++++++++++
1 file changed, 40 insertions(+)
diff --git a/problems/1365.有多少小于当前数字的数字.md b/problems/1365.有多少小于当前数字的数字.md
index 78fa84c0..ce1e77df 100644
--- a/problems/1365.有多少小于当前数字的数字.md
+++ b/problems/1365.有多少小于当前数字的数字.md
@@ -217,6 +217,46 @@ var smallerNumbersThanCurrent = function(nums) {
};
```
+TypeScript:
+
+> 暴力法:
+
+```typescript
+function smallerNumbersThanCurrent(nums: number[]): number[] {
+ const length: number = nums.length;
+ const resArr: number[] = [];
+ for (let i = 0; i < length; i++) {
+ let count: number = 0;
+ for (let j = 0; j < length; j++) {
+ if (nums[j] < nums[i]) {
+ count++;
+ }
+ }
+ resArr[i] = count;
+ }
+ return resArr;
+};
+```
+
+> 排序+hash
+
+```typescript
+function smallerNumbersThanCurrent(nums: number[]): number[] {
+ const length: number = nums.length;
+ const sortedArr: number[] = [...nums];
+ sortedArr.sort((a, b) => a - b);
+ const hashMap: Map = new Map();
+ for (let i = length - 1; i >= 0; i--) {
+ hashMap.set(sortedArr[i], i);
+ }
+ const resArr: number[] = [];
+ for (let i = 0; i < length; i++) {
+ resArr[i] = hashMap.get(nums[i]);
+ }
+ return resArr;
+};
+```
+
-----------------------
From f83d5edb6ebf5cd6de1eabba51a246a921f94e1b Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Mon, 23 May 2022 19:14:45 +0800
Subject: [PATCH 158/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200222.=E5=AE=8C?=
=?UTF-8?q?=E5=85=A8=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82=E7=82=B9?=
=?UTF-8?q?=E4=B8=AA=E6=95=B0.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0222.完全二叉树的节点个数.md | 63 +++++++++++++++++++++++++++
1 file changed, 63 insertions(+)
diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md
index ba7acc5a..746d45cc 100644
--- a/problems/0222.完全二叉树的节点个数.md
+++ b/problems/0222.完全二叉树的节点个数.md
@@ -646,5 +646,68 @@ func countNodes(_ root: TreeNode?) -> Int {
}
```
+## Scala
+
+递归:
+```scala
+object Solution {
+ def countNodes(root: TreeNode): Int = {
+ if(root == null) return 0
+ 1 + countNodes(root.left) + countNodes(root.right)
+ }
+}
+```
+
+层序遍历:
+```scala
+object Solution {
+ import scala.collection.mutable
+ def countNodes(root: TreeNode): Int = {
+ if (root == null) return 0
+ val queue = mutable.Queue[TreeNode]()
+ var node = 0
+ queue.enqueue(root)
+ while (!queue.isEmpty) {
+ val len = queue.size
+ for (i <- 0 until len) {
+ node += 1
+ val curNode = queue.dequeue()
+ if (curNode.left != null) queue.enqueue(curNode.left)
+ if (curNode.right != null) queue.enqueue(curNode.right)
+ }
+ }
+ node
+ }
+}
+```
+
+利用完全二叉树性质:
+```scala
+object Solution {
+ def countNodes(root: TreeNode): Int = {
+ if (root == null) return 0
+ var leftNode = root.left
+ var rightNode = root.right
+ // 向左向右往下探
+ var leftDepth = 0
+ while (leftNode != null) {
+ leftDepth += 1
+ leftNode = leftNode.left
+ }
+ var rightDepth = 0
+ while (rightNode != null) {
+ rightDepth += 1
+ rightNode = rightNode.right
+ }
+ // 如果相等就是一个满二叉树
+ if (leftDepth == rightDepth) {
+ return (2 << leftDepth) - 1
+ }
+ // 如果不相等就不是一个完全二叉树,继续向下递归
+ countNodes(root.left) + countNodes(root.right) + 1
+ }
+}
+```
+
-----------------------
From 45a3c91a7a954947d6b7373bee876d2f498e26bd Mon Sep 17 00:00:00 2001
From: ZongqinWang <1722249371@qq.com>
Date: Mon, 23 May 2022 19:49:18 +0800
Subject: [PATCH 159/162] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200257.=E4=BA=8C?=
=?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF=E5=BE=84?=
=?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/0257.二叉树的所有路径.md | 30 ++++++++++++++++++++++++++++++
1 file changed, 30 insertions(+)
diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md
index 1362897c..70a3c66f 100644
--- a/problems/0257.二叉树的所有路径.md
+++ b/problems/0257.二叉树的所有路径.md
@@ -702,5 +702,35 @@ func binaryTreePaths(_ root: TreeNode?) -> [String] {
}
```
+Scala:
+
+递归:
+```scala
+object Solution {
+ import scala.collection.mutable.ListBuffer
+ def binaryTreePaths(root: TreeNode): List[String] = {
+ val res = ListBuffer[String]()
+ def traversal(curNode: TreeNode, path: ListBuffer[Int]): Unit = {
+ path.append(curNode.value)
+ if (curNode.left == null && curNode.right == null) {
+ res.append(path.mkString("->")) // mkString函数: 将数组的所有值按照指定字符串拼接
+ return // 处理完可以直接return
+ }
+
+ if (curNode.left != null) {
+ traversal(curNode.left, path)
+ path.remove(path.size - 1)
+ }
+ if (curNode.right != null) {
+ traversal(curNode.right, path)
+ path.remove(path.size - 1)
+ }
+ }
+ traversal(root, ListBuffer[Int]())
+ res.toList
+ }
+}
+```
+
-----------------------
From 0281b82d48a4f21429d35a89270843357f801c15 Mon Sep 17 00:00:00 2001
From: SevenMonths
Date: Mon, 16 May 2022 15:26:21 +0800
Subject: [PATCH 160/162] =?UTF-8?q?=E5=A2=9E=E5=8A=A0php=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
problems/剑指Offer58-II.左旋转字符串.md | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md
index fec83e1d..8781ffb4 100644
--- a/problems/剑指Offer58-II.左旋转字符串.md
+++ b/problems/剑指Offer58-II.左旋转字符串.md
@@ -290,6 +290,25 @@ func reverseString(_ s: inout [Character], startIndex: Int, endIndex: Int) {
}
```
+### PHP
+
+```php
+function reverseLeftWords($s, $n) {
+ $this->reverse($s,0,$n-1); //反转区间为前n的子串
+ $this->reverse($s,$n,strlen($s)-1); //反转区间为n到末尾的子串
+ $this->reverse($s,0,strlen($s)-1); //反转整个字符串
+ return $s;
+}
+
+// 按指定进行翻转 【array、string都可】
+function reverse(&$s, $start, $end) {
+ for ($i = $start, $j = $end; $i < $j; $i++, $j--) {
+ $tmp = $s[$i];
+ $s[$i] = $s[$j];
+ $s[$j] = $tmp;
+ }
+}
+```
From f5f5f5a2a530845483708938064c05aae698487c Mon Sep 17 00:00:00 2001
From: programmercarl <826123027@qq.com>
Date: Fri, 10 Jun 2022 11:02:44 +0800
Subject: [PATCH 161/162] Update
---
problems/0027.移除元素.md | 14 +-
problems/0035.搜索插入位置.md | 12 +-
problems/0704.二分查找.md | 2 +
problems/0977.有序数组的平方.md | 2 +
problems/qita/gitserver.md | 312 ++++++++++++++++++++++++++
problems/qita/server.md | 126 +++++++++++
problems/{其他 => qita}/参与本项目.md | 0
7 files changed, 460 insertions(+), 8 deletions(-)
create mode 100644 problems/qita/gitserver.md
create mode 100644 problems/qita/server.md
rename problems/{其他 => qita}/参与本项目.md (100%)
diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md
index 590cf0b9..72860ffd 100644
--- a/problems/0027.移除元素.md
+++ b/problems/0027.移除元素.md
@@ -28,6 +28,8 @@
## 思路
+[本题B站视频讲解](https://www.bilibili.com/video/BV12A4y1Z7LP)
+
有的同学可能说了,多余的元素,删掉不就得了。
**要知道数组的元素在内存地址中是连续的,不能单独删除数组中的某个元素,只能覆盖。**
@@ -75,10 +77,20 @@ public:
双指针法(快慢指针法): **通过一个快指针和慢指针在一个for循环下完成两个for循环的工作。**
+定义快慢指针
+
+* 快指针:寻找新数组的元素 ,新数组就是不含有目标元素的数组
+* 慢指针:指向更新 新数组下标的位置
+
+很多同学这道题目做的很懵,就是不理解 快慢指针究竟都是什么含义,所以一定要明确含义,后面的思路就更容易理解了。
+
删除过程如下:

+很多同学不了解
+
+
**双指针法(快慢指针法)在数组和链表的操作中是非常常见的,很多考察数组、链表、字符串等操作的面试题,都使用双指针法。**
后序都会一一介绍到,本题代码如下:
@@ -104,8 +116,6 @@ public:
* 时间复杂度:O(n)
* 空间复杂度:O(1)
-旧文链接:[数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html)
-
```CPP
/**
* 相向双指针方法,基于元素顺序可以改变的题目描述改变了元素相对位置,确保了移动最少元素
diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md
index 8a8f9706..ff1b0292 100644
--- a/problems/0035.搜索插入位置.md
+++ b/problems/0035.搜索插入位置.md
@@ -73,8 +73,8 @@ public:
};
```
-* 时间复杂度:$O(n)$
-* 空间复杂度:$O(1)$
+* 时间复杂度:O(n)
+* 空间复杂度:O(1)
效率如下:
@@ -135,14 +135,14 @@ public:
// 目标值在数组所有元素之前 [0, -1]
// 目标值等于数组中某一个元素 return middle;
// 目标值插入数组中的位置 [left, right],return right + 1
- // 目标值在数组所有元素之后的情况 [left, right], return right + 1
+ // 目标值在数组所有元素之后的情况 [left, right], 因为是右闭区间,所以 return right + 1
return right + 1;
}
};
```
-* 时间复杂度:$O(\log n)$
-* 时间复杂度:$O(1)$
+* 时间复杂度:O(log n)
+* 时间复杂度:O(1)
效率如下:

@@ -178,7 +178,7 @@ public:
// 目标值在数组所有元素之前 [0,0)
// 目标值等于数组中某一个元素 return middle
// 目标值插入数组中的位置 [left, right) ,return right 即可
- // 目标值在数组所有元素之后的情况 [left, right),return right 即可
+ // 目标值在数组所有元素之后的情况 [left, right),因为是右开区间,所以 return right
return right;
}
};
diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md
index 55625130..ce8253af 100644
--- a/problems/0704.二分查找.md
+++ b/problems/0704.二分查找.md
@@ -36,6 +36,8 @@
## 思路
+为了易于大家理解,我还录制了视频,可以看这里:[手把手带你撕出正确的二分法](https://www.bilibili.com/video/BV1fA4y1o715)
+
**这道题目的前提是数组为有序数组**,同时题目还强调**数组中无重复元素**,因为一旦有重复元素,使用二分查找法返回的元素下标可能不是唯一的,这些都是使用二分法的前提条件,当大家看到题目描述满足如上条件的时候,可要想一想是不是可以用二分法了。
二分查找涉及的很多的边界条件,逻辑比较简单,但就是写不好。例如到底是 `while(left < right)` 还是 `while(left <= right)`,到底是`right = middle`呢,还是要`right = middle - 1`呢?
diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md
index 24276bcf..8811f3d7 100644
--- a/problems/0977.有序数组的平方.md
+++ b/problems/0977.有序数组的平方.md
@@ -23,6 +23,8 @@
# 思路
+为了易于大家理解,我还特意录制了视频,[本题视频讲解](https://www.bilibili.com/video/BV1QB4y1D7ep)
+
## 暴力排序
最直观的想法,莫过于:每个数平方之后,排个序,美滋滋,代码如下:
diff --git a/problems/qita/gitserver.md b/problems/qita/gitserver.md
new file mode 100644
index 00000000..9ee06ae4
--- /dev/null
+++ b/problems/qita/gitserver.md
@@ -0,0 +1,312 @@
+
+# 一文手把手教你搭建Git私服
+
+## 为什么要搭建Git私服
+
+很多同学都问文章,文档,资料怎么备份啊,自己电脑和公司电脑怎么随时同步资料啊等等,这里呢我写一个搭建自己的git私服的详细教程
+
+为什么要搭建一个Git私服呢,而不是用Github免费的私有仓库,有以下几点:
+* Github 私有仓库真的慢,文件一旦多了,或者有图片文件,git pull 的时候半天拉不下来
+* 自己的文档难免有自己个人信息,放在github心里也是担心的
+* 想建几个库就建几个,想几个人合作开发都可以,不香么?
+
+**网上可以搜到很多git搭建,但是说的模棱两可**,而且有的直接是在本地搭建git服务,既然是备份,搭建在本地哪有备份的意义,一定要有一个远端服务器, 而且自己的电脑和公司的电脑还是同步自己的文章,文档和资料等等。
+
+
+适合人群: 想通过git私服来备份自己的文章,Markdown,并做版本管理的同学
+最后,写好每篇 Chat 是对我的责任,也是对你的尊重。谢谢大家~
+
+正文如下:
+
+-----------------------------
+
+## 如何找到可以外网访问服务器
+
+有的同学问了,自己的电脑就不能作为服务器么?
+
+这里要说一下,安装家庭带宽,运营商默认是不会给我们独立分配公网IP的
+
+一般情况下是一片区域公用一个公网IP池,所以外网是不能访问到在家里我们使用的电脑的
+
+除非我们自己去做映射,这其实非常麻烦而且公网IP池 是不断变化的
+
+辛辛苦苦做了映射,运营商给IP一换,我们的努力就白扯了
+
+那我们如何才能找到一个外网可以访问的服务器呢,此时云计算拯救了我们。
+
+推荐大家选一家云厂商(阿里云,腾讯云,百度云都可以)在上面上买一台云服务器
+
+* [阿里云活动期间服务器购买](https://www.aliyun.com/minisite/goods?taskCode=shareNew2205&recordId=3641992&userCode=roof0wob)
+* [腾讯云活动期间服务器购买](https://curl.qcloud.com/EiaMXllu)
+
+云厂商经常做活动,如果从来没有买过云服务器的账号更便宜,低配一年一百块左右的样子,强烈推荐一起买个三年。
+
+买云服务器的时候推荐直接安装centos系统。
+
+这里要说一下,有了自己的云服务器之后 不仅仅可以用来做git私服
+
+**同时还可以做网站,做程序后台,跑程序,做测试**(这样我们自己的电脑就不会因为自己各种搭建环境下载各种包而搞的的烂糟糟),等等等。
+
+有自己云服务器和一个公网IP真的是一件非常非常幸福的事情,能体验到自己的服务随时可以部署上去提供给所有人使用的喜悦。
+
+外网可以访问的服务器解决了,接下来就要部署git服务了
+
+本文将采用centos系统来部署git私服
+
+## 服务器端安装Git
+
+切换至root账户
+
+```
+su root
+```
+
+看一下服务器有没有安装git,如果出现下面信息就说明是有git的
+```
+[root@instance-5fcyjde7 ~]# git
+usage: git [--version] [--help] [-c name=value]
+ [--exec-path[=]] [--html-path] [--man-path] [--info-path]
+ [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
+ [--git-dir=] [--work-tree=] [--namespace=]
+ []
+
+The most commonly used git commands are:
+ add Add file contents to the index
+ bisect Find by binary search the change that introduced a bug
+ branch List, create, or delete branches
+ checkout Checkout a branch or paths to the working tree
+ clone Clone a repository into a new directory
+ commit Record changes to the repository
+ diff Show changes between commits, commit and working tree, etc
+ fetch Download objects and refs from another repository
+ grep Print lines matching a pattern
+ init Create an empty Git repository or reinitialize an existing one
+ log Show commit logs
+ merge Join two or more development histories together
+ mv Move or rename a file, a directory, or a symlink
+ pull Fetch from and merge with another repository or a local branch
+ push Update remote refs along with associated objects
+ rebase Forward-port local commits to the updated upstream head
+ reset Reset current HEAD to the specified state
+ rm Remove files from the working tree and from the index
+ show Show various types of objects
+ status Show the working tree status
+ tag Create, list, delete or verify a tag object signed with GPG
+
+'git help -a' and 'git help -g' lists available subcommands and some
+concept guides. See 'git help ' or 'git help '
+to read about a specific subcommand or concept.
+```
+
+如果没有git,就安装一下,yum安装的版本默认是 `1.8.3.1`
+
+```
+yum install git
+```
+
+安装成功之后,看一下自己安装的版本
+
+```
+git --version
+```
+
+## 服务器端设置Git账户
+
+创建一个git的linux账户,这个账户只做git私服的操作,也是为了安全起见
+
+如果不新创建一个linux账户,在自己的常用的linux账户下创建的话,哪天手抖 来一个`rm -rf *` 操作 数据可全没了
+
+**这里linux git账户的密码设置的尽量复杂一些,我这里为了演示,就设置成为'gitpassword'**
+```
+adduser git
+passwd gitpassword
+```
+
+然后就要切换成git账户,进行后面的操作了
+```
+[root@instance-5fcyjde7 ~]# su - git
+```
+
+看一下自己所在的目录,是不是在git目录下面
+
+```
+[git@instance-5fcyjde7 ~]$ pwd
+/home/git
+```
+
+## 服务器端密钥管理
+
+创建`.ssh` 目录,如果`.ssh` 已经存在了,可以忽略这一项
+
+为啥用配置ssh公钥呢,同学们记不记得我急使用github上传上传代码的时候也要把自己的公钥配置上github上
+
+这也是方面每次操作git仓库的时候不用再去输入密码
+
+```
+cd ~/
+mkdir .ssh
+```
+
+进入.ssh 文件下,创建一个 `authorized_keys` 文件,这个文件就是后面就是要放我们客户端的公钥
+
+```
+cd ~/.ssh
+touch authorized_keys
+```
+
+别忘了`authorized_keys`给设置权限,很多同学发现自己不能免密登陆,都是因为忘记了给`authorized_keys` 设置权限
+
+```
+chmod 700 /home/git/.ssh
+chmod 600 /home/git/.ssh/authorized_keys
+```
+
+接下来我们要把客户端的公钥放在git服务器上,我们在回到客户端,创建一个公钥
+
+在我们自己的电脑上,有公钥和私钥 两个文件分别是:`id_rsa` 和 `id_rsa.pub`
+
+如果是`windows`系统公钥私钥的目录在`C:\Users\用户名\.ssh` 下
+
+如果是mac 或者 linux, 公钥和私钥的目录这里 `cd ~/.ssh/`, 如果发现自己的电脑上没有公钥私钥,那就自己创建一个
+
+创建密钥的命令
+
+```
+ssh-keygen -t rsa
+```
+
+创建密钥的过程中,一路点击回车就可以了。不需要填任何东西
+
+把公钥拷贝到git服务器上,将我们刚刚生成的`id_rsa.pub`,拷贝到git服务器的`/home/git/.ssh/`目录
+
+在git服务器上,将公钥添加到`authorized_keys` 文件中
+
+```
+cd /home/git/.ssh/
+cat id_rsa.pub >> authorized_keys
+```
+
+如何看我们配置的密钥是否成功呢, 在客户点直接登录git服务器,看看是否是免密登陆
+```
+ssh git@git服务器ip
+```
+
+例如:
+
+```
+ssh git@127.0.0.1
+```
+
+如果可以免密登录,那就说明服务器端密钥配置成功了
+
+## 服务器端部署Git 仓库
+
+我们在登陆到git 服务器端,切换为成 git账户
+
+如果是root账户切换成git账户
+```
+su - git
+```
+
+如果是其他账户切换为git账户
+```
+sudo su - git
+```
+
+进入git目录下
+```
+cd ~/git
+```
+
+创建我们的第一个Git私服的仓库,我们叫它为world仓库
+
+那么首先创建一个文件夹名为: world.git ,然后进入这个目录
+
+有同学问,为什么文件夹名字后面要放`.git`, 其实不这样命名也是可以的
+
+但是细心的同学可能注意到,我们平时在github上 `git clone` 其他人的仓库的时候,仓库名字后面,都是加上`.git`的
+
+例如下面这个例子,其实就是github对仓库名称的一个命名规则,所以我们也遵守github的命名规则。
+
+```
+git clone https://github.com/youngyangyang04/NoSQLAttack.git
+```
+
+所以我们的操作是
+```
+[git@localhost git]# mkdir world.git
+[git@localhost git]# cd world.git
+```
+
+初始化我们的`world`仓库
+
+```
+git init --bare
+
+```
+
+**如果我们想创建多个仓库,就在这里创建多个文件夹并初始化就可以了,和world仓库的操作过程是一样一样的**
+
+现在我们服务端的git仓库就部署完了,接下来就看看客户端,如何使用这个仓库呢
+
+## 客户端连接远程仓库
+
+我们在自己的电脑上创建一个文件夹 也叫做`world`吧
+
+其实这里命名是随意的,但是我们为了和git服务端的仓库名称保持同步。 这样更直观我们操作的是哪一个仓库。
+
+```
+mkdir world
+cd world
+```
+
+进入world文件,并初始化操作
+
+```
+cd world
+git init
+```
+
+在world目录上创建一个测试文件,并且将其添加到git版本管理中
+
+```
+touch test
+git add test
+git commit -m "add test file"
+```
+
+将次仓库和远端仓库同步
+
+```
+git remote add origin git@git服务器端的ip:world.git
+git push -u origin master
+```
+
+此时这个test测试文件就已经提交到我们的git远端私服上了
+
+## Git私服安全问题
+
+这里有两点安全问题
+
+### linux git的密码不要泄露出去
+
+否则,别人可以通过 ssh git@git服务器IP 来登陆到你的git私服服务器上
+
+当然了,这里同学们如果买的是云厂商的云服务器的话
+
+如果有人恶意想通过 尝试不同密码链接的方式来链接你的服务器,重试三次以上
+
+这个客户端的IP就会被封掉,同时邮件通知我们可以IP来自哪里
+
+所以大可放心 密码只要我们不泄露出去,基本上不会有人同时不断尝试密码的方式来登上我们的git私服服务器
+
+### 私钥文件`id_rsa` 不要给别人
+
+如果有人得到了这个私钥,就可以免密码登陆我们的git私服上了,我相信大家也不至于把自己的私钥主动给别人吧
+
+## 总结
+
+这里就是整个git私服搭建的全过程,安全问题我也给大家列举了出来,接下来好好享受自己的Git私服吧
+
+**enjoy!**
+
diff --git a/problems/qita/server.md b/problems/qita/server.md
new file mode 100644
index 00000000..16995d70
--- /dev/null
+++ b/problems/qita/server.md
@@ -0,0 +1,126 @@
+
+# 一台服务器有什么用!
+
+但在组织这场活动的时候,了解到大家都有一个共同的问题: **这个服务器究竟有啥用??**
+
+这真是一个好问题,而且我一句两句还说不清楚,所以就专门发文来讲一讲。
+
+同时我还录制的一期视频,哈哈我的视频号,大家可以关注一波。
+
+
+一说到服务器,可能很多人都说搞分布式,做计算,搞爬虫,做程序后台服务,多人合作等等。
+
+其实这些普通人都用不上,我来说一说大家能用上的吧。
+
+## 搭建git私服
+
+大家平时工作的时候一定有一个自己的工作文件夹,学生的话就是自己的课件,考试,准备面试的资料等等。
+
+已经工作的录友,会有一个文件夹放着自己重要的文档,Markdown,图片,简历等等。
+
+这么重要的文件夹,而且我们每天都要更新,也担心哪天电脑丢了,或者坏了,突然这些都不见了。
+
+所以我们想备份嘛。
+
+还有就是我们经常个人电脑和工作电脑要同步一些私人资料,而不是用微信传来传去。
+
+这些都是git私服的使用场景,而且很好用。
+
+大家也知道 github,gitee也可以搞私人仓库 用来备份,同步文件,但自己的文档可能放着很多重要的信息,包括自己的各种密码,密钥之类的,放到上面未必安全。你就不怕哪些重大bug把你的信息都泄漏了么[机智]
+
+更关键的是,github 和 gitee都限速的。毕竟人家的功能定位并不是网盘。
+
+项目里有大文件(几百M以上),例如pdf,ppt等等 其上传和下载速度会让你窒息。
+
+**后面我会发文专门来讲一讲,如何大家git私服!**
+
+## 搞一个文件存储
+
+这个可以用来生成文件的下载链接,也可以把本地文件传到服务器上。
+
+相当于自己做一个对象存储,其实云厂商也有对象存储的产品。
+
+不过我们自己也可以做一个,不够很多很同学应该都不知道对象存储怎么用吧,其实我们用服务器可以自己做一个类似的公司。
+
+我现在就用自己用go写的一个工具,部署在服务器上。 用来和服务器传文件,或者生成一些文件的临时下载链接。
+
+这些都是直接命令行操作的,
+
+操作方式这样,我把命令包 包装成一个shell命令,想传那个文件,直接 uploadtomyserver,然后就返回可以下载的链接,这个文件也同时传到了我的服务器上。
+
+
+
+我也把我的项目代码放在了github上:
+
+https://github.com/youngyangyang04/fileHttpServer
+
+感兴趣的录友可以去学习一波,顺便给个star 哈哈
+
+
+## 网站
+
+做网站,例如 大家知道用html 写几行代码,就可以生成一个网页,但怎么给别人展示呢?
+
+大家如果用自己的电脑做服务器,只能同一个路由器下的设备可以访问你的网站,可能这个设备出了这个屋子 都访问不了你的网站了。
+
+因为你的IP不是公网IP。
+
+如果有了一台云服务器,都是配公网IP,你的网站就可以让任何人访问了。
+
+或者说 你提供的一个服务就可以让任何人使用。
+
+例如第二个例子中,我们可以自己开发一个文件存储,这个服务,我只把把命令行给其他人,其他人都可以使用我的服务来生成链接,当然他们的文件也都传到了我的服务器上。
+
+再说一个使用场景。
+
+我之前在组织免费里服务器的活动的时候,阿里云给我一个excel,让面就是从我这里买服务器录友的名单,我直接把这个名单甩到群里,让大家自己检查,出现在名单里就可以找我返现,这样做是不是也可以。
+
+这么做有几个很大的问题:
+* 大家都要去下载excel,做对比,会有人改excel的内容然后就说是从你这里买的,我不可能挨个去比较excel有没有改动
+* excel有其他人的个人信息,这是不能暴漏的。
+* 如果每个人自己用excel查询,私信我返现,一个将近两千人找我返现,我微信根本处理不过来,这就变成体力活了。
+
+那应该怎么做呢,
+
+我就简单写一个查询的页面,后端逻辑就是读一个execel表格,大家在查询页面输入自己的阿里云ID,如果在excel里,页面就会返回返现群的二维码,大家就可以自主扫码加群了。
+
+这样,我最后就直接在返现群里 发等额红包就好了,是不是极大降低人力成本了
+
+当然我是把 17个返现群的二维码都生成好了,按照一定的规则,展现给查询通过的录友。
+
+就是这样一个非常普通的查询页面。
+
+
+
+查询通过之后,就会展现返现群二维码。
+
+
+
+但要部署在服务器上,因为没有公网IP,别人用不了你的服务。
+
+
+## 学习linux
+
+学习linux其实在自己的电脑上搞一台虚拟机,或者安装双系统也可以学习,不过这很考验你的电脑性能如何了。
+
+如果你有一个服务器,那就是独立的一台电脑,你怎么霍霍就怎么霍霍,而且一年都不用关机的,可以一直跑你的任务,和你本地电脑也完全隔离。
+
+更方便的是,你目前系统假如是centos,想做一个实验需要在unbantu上,如果是云服务器,更换系统就是在 后台点一下,一键重装,云厂商基本都是支持所有系统一件安装的。
+
+我们平时自己玩linux经常是配各种环境,然后这个linux就被自己玩坏了(一般都是毫无节制使用root权限导致的),总之就是环境配不起来了,基本就要重装了。
+
+那云服务器重装系统可太方便了。
+
+还有就是加入你好不容易配好的环境,如果以后把这个环境玩坏了,你先回退这之前配好的环境而不是重装系统在重新配一遍吧。
+
+那么可以用云服务器的镜像保存功能,就是你配好环境的那一刻就可以打一个镜像包,以后如果环境坏了,直接回退到上次镜像包的状态,这是不是就很香了。
+
+
+## 总结
+
+其实云服务器还有很多其他用处,不过我就说一说大家普遍能用的上的。
+
+
+* [阿里云活动期间服务器购买](https://www.aliyun.com/minisite/goods?taskCode=shareNew2205&recordId=3641992&userCode=roof0wob)
+* [腾讯云活动期间服务器购买](https://curl.qcloud.com/EiaMXllu)
+
diff --git a/problems/其他/参与本项目.md b/problems/qita/参与本项目.md
similarity index 100%
rename from problems/其他/参与本项目.md
rename to problems/qita/参与本项目.md
From 2c1aa6ebf83cca21a8c6536922f2d652fa45c5cc Mon Sep 17 00:00:00 2001
From: programmercarl <826123027@qq.com>
Date: Mon, 13 Jun 2022 17:23:30 +0800
Subject: [PATCH 162/162] Update
---
problems/0202.快乐数.md | 1 +
problems/0209.长度最小的子数组.md | 29 +++++++++++++++++++++++------
problems/0349.两个数组的交集.md | 2 ++
problems/0383.赎金信.md | 1 +
problems/0454.四数相加II.md | 1 +
problems/qita/server.md | 3 +++
6 files changed, 31 insertions(+), 6 deletions(-)
diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md
index be8686f7..7738b2f6 100644
--- a/problems/0202.快乐数.md
+++ b/problems/0202.快乐数.md
@@ -417,6 +417,7 @@ object Solution {
}
sum
}
+```
C#:
diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md
index fbef7692..69e0da4f 100644
--- a/problems/0209.长度最小的子数组.md
+++ b/problems/0209.长度最小的子数组.md
@@ -5,7 +5,7 @@
参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!
-## 209.长度最小的子数组
+# 209.长度最小的子数组
[力扣题目链接](https://leetcode-cn.com/problems/minimum-size-subarray-sum/)
@@ -17,6 +17,9 @@
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
+# 思路
+
+为了易于大家理解,我特意录制了[拿下滑动窗口! | LeetCode 209 长度最小的子数组](https://www.bilibili.com/video/BV1tZ4y1q7XE)
## 暴力解法
@@ -47,8 +50,8 @@ public:
}
};
```
-时间复杂度:O(n^2)
-空间复杂度:O(1)
+* 时间复杂度:O(n^2)
+* 空间复杂度:O(1)
## 滑动窗口
@@ -56,6 +59,20 @@ public:
所谓滑动窗口,**就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果**。
+在暴力解法中,是一个for循环滑动窗口的起始位置,一个for循环为滑动窗口的终止位置,用两个for循环 完成了一个不断搜索区间的过程。
+
+那么滑动窗口如何用一个for循环来完成这个操作呢。
+
+首先要思考 如果用一个for循环,那么应该表示 滑动窗口的起始位置,还是终止位置。
+
+如果只用一个for循环来表示 滑动窗口的起始位置,那么如何遍历剩下的终止位置?
+
+此时难免再次陷入 暴力解法的怪圈。
+
+所以 只用一个for循环,那么这个循环的索引,一定是表示 滑动窗口的终止位置。
+
+那么问题来了, 滑动窗口的起始位置如何移动呢?
+
这里还是以题目中的示例来举例,s=7, 数组是 2,3,1,2,4,3,来看一下查找的过程:

@@ -74,7 +91,7 @@ public:
窗口的起始位置如何移动:如果当前窗口的值大于s了,窗口就要向前移动了(也就是该缩小了)。
-窗口的结束位置如何移动:窗口的结束位置就是遍历数组的指针,窗口的起始位置设置为数组的起始位置就可以了。
+窗口的结束位置如何移动:窗口的结束位置就是遍历数组的指针,也就是for循环里的索引。
解题的关键在于 窗口的起始位置如何移动,如图所示:
@@ -107,8 +124,8 @@ public:
};
```
-时间复杂度:O(n)
-空间复杂度:O(1)
+* 时间复杂度:O(n)
+* 空间复杂度:O(1)
**一些录友会疑惑为什么时间复杂度是O(n)**。
diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md
index f7dab3d7..4fbdd414 100644
--- a/problems/0349.两个数组的交集.md
+++ b/problems/0349.两个数组的交集.md
@@ -356,6 +356,8 @@ object Solution {
}
}
+```
+
C#:
```csharp
diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md
index 75dafb72..9c3dda8c 100644
--- a/problems/0383.赎金信.md
+++ b/problems/0383.赎金信.md
@@ -425,6 +425,7 @@ object Solution {
true
}
}
+```
C#:
diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md
index bfdee26e..726fdb15 100644
--- a/problems/0454.四数相加II.md
+++ b/problems/0454.四数相加II.md
@@ -354,6 +354,7 @@ object Solution {
res
}
}
+```
C#:
```csharp
diff --git a/problems/qita/server.md b/problems/qita/server.md
index 16995d70..1d7a1d6b 100644
--- a/problems/qita/server.md
+++ b/problems/qita/server.md
@@ -1,6 +1,9 @@
# 一台服务器有什么用!
+* [阿里云活动期间服务器购买](https://www.aliyun.com/minisite/goods?taskCode=shareNew2205&recordId=3641992&userCode=roof0wob)
+* [腾讯云活动期间服务器购买](https://curl.qcloud.com/EiaMXllu)
+
但在组织这场活动的时候,了解到大家都有一个共同的问题: **这个服务器究竟有啥用??**
这真是一个好问题,而且我一句两句还说不清楚,所以就专门发文来讲一讲。