Skip to content

Commit f1c36e1

Browse files
authored
Merge branch 'youngyangyang04:master' into master
2 parents c0f1f13 + fd25f8f commit f1c36e1

10 files changed

+403
-41
lines changed

problems/0063.不同路径II.md

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -272,24 +272,28 @@ class Solution:
272272
row = len(obstacleGrid)
273273
col = len(obstacleGrid[0])
274274
dp = [[0 for _ in range(col)] for _ in range(row)]
275-
276-
dp[0][0] = 1 if obstacleGrid[0][0] != 1 else 0
277-
if dp[0][0] == 0: return 0 # 如果第一个格子就是障碍,return 0
275+
dp[0][0] = 0 if obstacleGrid[0][0] == 1 else 1
276+
if dp[0][0] == 0:
277+
return 0 # 如果第一个格子就是障碍,return 0
278278
# 第一行
279279
for i in range(1, col):
280-
if obstacleGrid[0][i] != 1:
281-
dp[0][i] = dp[0][i-1]
280+
if obstacleGrid[0][i] == 1:
281+
# 遇到障碍物时,直接退出循环,后面默认都是0
282+
break
283+
dp[0][i] = 1
282284

283285
# 第一列
284286
for i in range(1, row):
285-
if obstacleGrid[i][0] != 1:
286-
dp[i][0] = dp[i-1][0]
287-
print(dp)
287+
if obstacleGrid[i][0] == 1:
288+
# 遇到障碍物时,直接退出循环,后面默认都是0
289+
break
290+
dp[i][0] = 1
291+
# print(dp)
288292

289293
for i in range(1, row):
290294
for j in range(1, col):
291-
if obstacleGrid[i][j] != 1:
292-
dp[i][j] = dp[i-1][j] + dp[i][j-1]
295+
if obstacleGrid[i][j] == 0:
296+
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
293297
return dp[-1][-1]
294298
```
295299

problems/0101.对称二叉树.md

Lines changed: 60 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -754,23 +754,77 @@ func isSymmetric3(_ root: TreeNode?) -> Bool {
754754

755755
## Scala
756756

757-
递归:
757+
> 递归:
758758
```scala
759-
object Solution {
759+
object Solution {
760760
def isSymmetric(root: TreeNode): Boolean = {
761761
if (root == null) return true // 如果等于空直接返回true
762+
762763
def compare(left: TreeNode, right: TreeNode): Boolean = {
763-
if (left == null && right == null) return true // 如果左右都为空,则为true
764-
if (left == null && right != null) return false // 如果左空右不空,不对称,返回false
765-
if (left != null && right == null) return false // 如果左不空右空,不对称,返回false
764+
if (left == null && right == null) true // 如果左右都为空,则为true
765+
else if (left == null && right != null) false // 如果左空右不空,不对称,返回false
766+
else if (left != null && right == null) false // 如果左不空右空,不对称,返回false
766767
// 如果左右的值相等,并且往下递归
767-
left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
768+
else left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
768769
}
770+
769771
// 分别比较左子树和右子树
770772
compare(root.left, root.right)
771773
}
772774
}
773775
```
776+
> 迭代 - 使用栈
777+
```scala
778+
object Solution {
779+
780+
import scala.collection.mutable
781+
782+
def isSymmetric(root: TreeNode): Boolean = {
783+
if (root == null) return true
784+
785+
val cache = mutable.Stack[(TreeNode, TreeNode)]((root.left, root.right))
786+
787+
while (cache.nonEmpty) {
788+
cache.pop() match {
789+
case (null, null) =>
790+
case (_, null) => return false
791+
case (null, _) => return false
792+
case (left, right) =>
793+
if (left.value != right.value) return false
794+
cache.push((left.left, right.right))
795+
cache.push((left.right, right.left))
796+
}
797+
}
798+
true
799+
}
800+
}
801+
```
802+
> 迭代 - 使用队列
803+
```scala
804+
object Solution {
805+
806+
import scala.collection.mutable
807+
808+
def isSymmetric(root: TreeNode): Boolean = {
809+
if (root == null) return true
810+
811+
val cache = mutable.Queue[(TreeNode, TreeNode)]((root.left, root.right))
812+
813+
while (cache.nonEmpty) {
814+
cache.dequeue() match {
815+
case (null, null) =>
816+
case (_, null) => return false
817+
case (null, _) => return false
818+
case (left, right) =>
819+
if (left.value != right.value) return false
820+
cache.enqueue((left.left, right.right))
821+
cache.enqueue((left.right, right.left))
822+
}
823+
}
824+
true
825+
}
826+
}
827+
```
774828

775829
<p align="center">
776830
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

problems/0242.有效的字母异位词.md

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,12 +123,11 @@ Python:
123123
class Solution:
124124
def isAnagram(self, s: str, t: str) -> bool:
125125
record = [0] * 26
126-
for i in range(len(s)):
126+
for i in s:
127127
#并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
128-
record[ord(s[i]) - ord("a")] += 1
129-
print(record)
130-
for i in range(len(t)):
131-
record[ord(t[i]) - ord("a")] -= 1
128+
record[ord(i) - ord("a")] += 1
129+
for i in t:
130+
record[ord(i) - ord("a")] -= 1
132131
for i in range(26):
133132
if record[i] != 0:
134133
#record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
@@ -154,6 +153,16 @@ class Solution:
154153

155154
return s_dict == t_dict
156155
```
156+
Python写法三(没有使用数组作为哈希表,只是介绍Counter这种更方便的解题思路):
157+
158+
```python
159+
class Solution(object):
160+
def isAnagram(self, s: str, t: str) -> bool:
161+
from collections import Counter
162+
a_count = Counter(s)
163+
b_count = Counter(t)
164+
return a_count == b_count
165+
```
157166

158167
Go:
159168

problems/0347.前K个高频元素.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,7 +487,34 @@ object Solution {
487487
.map(_._1)
488488
}
489489
}
490+
```
490491

492+
rust: 小根堆
493+
494+
```rust
495+
use std::cmp::Reverse;
496+
use std::collections::{BinaryHeap, HashMap};
497+
impl Solution {
498+
pub fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> {
499+
let mut hash = HashMap::new();
500+
let mut heap = BinaryHeap::with_capacity(k as usize);
501+
nums.into_iter().for_each(|k| {
502+
*hash.entry(k).or_insert(0) += 1;
503+
});
504+
505+
for (k, v) in hash {
506+
if heap.len() == heap.capacity() {
507+
if *heap.peek().unwrap() < (Reverse(v), k) {
508+
continue;
509+
} else {
510+
heap.pop();
511+
}
512+
}
513+
heap.push((Reverse(v), k));
514+
}
515+
heap.into_iter().map(|(_, k)| k).collect()
516+
}
517+
}
491518
```
492519

493520
<p align="center">

problems/0583.两个字符串的删除操作.md

Lines changed: 35 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -228,28 +228,43 @@ func min(a, b int) int {
228228
```
229229
Javascript:
230230
```javascript
231-
const minDistance = (word1, word2) => {
232-
let dp = Array.from(new Array(word1.length + 1), () => Array(word2.length+1).fill(0));
233-
234-
for(let i = 1; i <= word1.length; i++) {
235-
dp[i][0] = i;
236-
}
237-
238-
for(let j = 1; j <= word2.length; j++) {
239-
dp[0][j] = j;
231+
// 方法一
232+
var minDistance = (word1, word2) => {
233+
let dp = Array.from(new Array(word1.length + 1), () =>
234+
Array(word2.length + 1).fill(0)
235+
);
236+
for (let i = 1; i <= word1.length; i++) {
237+
dp[i][0] = i;
238+
}
239+
for (let j = 1; j <= word2.length; j++) {
240+
dp[0][j] = j;
241+
}
242+
for (let i = 1; i <= word1.length; i++) {
243+
for (let j = 1; j <= word2.length; j++) {
244+
if (word1[i - 1] === word2[j - 1]) {
245+
dp[i][j] = dp[i - 1][j - 1];
246+
} else {
247+
dp[i][j] = Math.min(
248+
dp[i - 1][j] + 1,
249+
dp[i][j - 1] + 1,
250+
dp[i - 1][j - 1] + 2
251+
);
252+
}
240253
}
254+
}
255+
return dp[word1.length][word2.length];
256+
};
241257

242-
for(let i = 1; i <= word1.length; i++) {
243-
for(let j = 1; j <= word2.length; j++) {
244-
if(word1[i-1] === word2[j-1]) {
245-
dp[i][j] = dp[i-1][j-1];
246-
} else {
247-
dp[i][j] = Math.min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + 2);
248-
}
249-
}
250-
}
251-
252-
return dp[word1.length][word2.length];
258+
// 方法二
259+
var minDistance = function (word1, word2) {
260+
let dp = new Array(word1.length + 1)
261+
.fill(0)
262+
.map((_) => new Array(word2.length + 1).fill(0));
263+
for (let i = 1; i <= word1.length; i++)
264+
for (let j = 1; j <= word2.length; j++)
265+
if (word1[i - 1] === word2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
266+
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
267+
return word1.length + word2.length - dp[word1.length][word2.length] * 2;
253268
};
254269
```
255270

problems/1254.统计封闭岛屿的数目.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,67 @@ public:
7676
return count;
7777
}
7878
};
79+
```
80+
## 其他语言版本
81+
82+
### JavaScript:
83+
84+
```js
85+
/**
86+
* @param {number[][]} grid
87+
* @return {number}
88+
*/
89+
var closedIsland = function(grid) {
90+
let rows = grid.length;
91+
let cols = grid[0].length;
92+
// 存储四个方向
93+
let dir = [[-1, 0], [0, -1], [1, 0], [0, 1]];
94+
// 深度优先
95+
function dfs(x, y) {
96+
grid[x][y] = 1;
97+
// 向四个方向遍历
98+
for(let i = 0; i < 4; i++) {
99+
let nextX = x + dir[i][0];
100+
let nextY = y + dir[i][1];
101+
// 判断是否越界
102+
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) continue;
103+
// 不符合条件
104+
if (grid[nextX][nextY] === 1) continue;
105+
// 继续递归
106+
dfs(nextX, nextY);
107+
}
108+
}
109+
// 从边界岛屿开始
110+
// 从左侧和右侧出发
111+
for(let i = 0; i < rows; i++) {
112+
if (grid[i][0] === 0) dfs(i, 0);
113+
if (grid[i][cols - 1] === 0) dfs(i, cols - 1);
114+
}
115+
// 从上侧和下侧出发
116+
for(let j = 0; j < cols; j++) {
117+
if (grid[0][j] === 0) dfs(0, j);
118+
if (grid[rows - 1][j] === 0) dfs(rows - 1, j);
119+
}
120+
let count = 0;
121+
// 排除所有与边界相连的陆地之后
122+
// 依次遍历网格中的每个元素,如果遇到一个元素是陆地且状态是未访问,则遇到一个新的岛屿,将封闭岛屿的数目加 1
123+
// 并访问与当前陆地连接的所有陆地
124+
for(let i = 0; i < rows; i++) {
125+
for(let j = 0; j < cols; j++) {
126+
if (grid[i][j] === 0) {
127+
count++;
128+
dfs(i, j);
129+
}
130+
}
131+
}
132+
return count;
133+
};
79134
```
135+
136+
80137
<p align="center">
81138
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
82139
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
83140
</a>
141+
142+

problems/二叉树理论基础.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,29 @@ class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null)
270270
var right: TreeNode = _right
271271
}
272272
```
273+
274+
rust:
275+
276+
```rust
277+
#[derive(Debug, PartialEq, Eq)]
278+
pub struct TreeNode<T> {
279+
pub val: T,
280+
pub left: Option<Rc<RefCell<TreeNode<T>>>>,
281+
pub right: Option<Rc<RefCell<TreeNode<T>>>>,
282+
}
283+
284+
impl<T> TreeNode<T> {
285+
#[inline]
286+
pub fn new(val: T) -> Self {
287+
TreeNode {
288+
val,
289+
left: None,
290+
right: None,
291+
}
292+
}
293+
}
294+
```
295+
273296
<p align="center">
274297
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
275298
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
 (0)