diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 547eb9f8..9aa36956 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -272,24 +272,28 @@ class Solution: row = len(obstacleGrid) col = len(obstacleGrid[0]) dp = [[0 for _ in range(col)] for _ in range(row)] - - dp[0][0] = 1 if obstacleGrid[0][0] != 1 else 0 - if dp[0][0] == 0: return 0 # 如果第一个格子就是障碍,return 0 + dp[0][0] = 0 if obstacleGrid[0][0] == 1 else 1 + if dp[0][0] == 0: + return 0 # 如果第一个格子就是障碍,return 0 # 第一行 for i in range(1, col): - if obstacleGrid[0][i] != 1: - dp[0][i] = dp[0][i-1] + if obstacleGrid[0][i] == 1: + # 遇到障碍物时,直接退出循环,后面默认都是0 + break + dp[0][i] = 1 # 第一列 for i in range(1, row): - if obstacleGrid[i][0] != 1: - dp[i][0] = dp[i-1][0] - print(dp) + if obstacleGrid[i][0] == 1: + # 遇到障碍物时,直接退出循环,后面默认都是0 + break + dp[i][0] = 1 + # print(dp) for i in range(1, row): for j in range(1, col): - if obstacleGrid[i][j] != 1: - dp[i][j] = dp[i-1][j] + dp[i][j-1] + if obstacleGrid[i][j] == 0: + dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[-1][-1] ``` diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 30ca3d77..37adfd54 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -754,23 +754,77 @@ func isSymmetric3(_ root: TreeNode?) -> Bool { ## Scala -递归: +> 递归: ```scala -object Solution { +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 + if (left == null && right == null) true // 如果左右都为空,则为true + else if (left == null && right != null) false // 如果左空右不空,不对称,返回false + else if (left != null && right == null) false // 如果左不空右空,不对称,返回false // 如果左右的值相等,并且往下递归 - left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left) + else left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left) } + // 分别比较左子树和右子树 compare(root.left, root.right) } } ``` +> 迭代 - 使用栈 +```scala +object Solution { + + import scala.collection.mutable + + def isSymmetric(root: TreeNode): Boolean = { + if (root == null) return true + + val cache = mutable.Stack[(TreeNode, TreeNode)]((root.left, root.right)) + + while (cache.nonEmpty) { + cache.pop() match { + case (null, null) => + case (_, null) => return false + case (null, _) => return false + case (left, right) => + if (left.value != right.value) return false + cache.push((left.left, right.right)) + cache.push((left.right, right.left)) + } + } + true + } +} +``` +> 迭代 - 使用队列 +```scala +object Solution { + + import scala.collection.mutable + + def isSymmetric(root: TreeNode): Boolean = { + if (root == null) return true + + val cache = mutable.Queue[(TreeNode, TreeNode)]((root.left, root.right)) + + while (cache.nonEmpty) { + cache.dequeue() match { + case (null, null) => + case (_, null) => return false + case (null, _) => return false + case (left, right) => + if (left.value != right.value) return false + cache.enqueue((left.left, right.right)) + cache.enqueue((left.right, right.left)) + } + } + true + } +} +```

diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index f8ebc545..1281b16b 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -123,12 +123,11 @@ Python: class Solution: def isAnagram(self, s: str, t: str) -> bool: record = [0] * 26 - for i in range(len(s)): + for i in s: #并不需要记住字符a的ASCII,只要求出一个相对数值就可以了 - record[ord(s[i]) - ord("a")] += 1 - print(record) - for i in range(len(t)): - record[ord(t[i]) - ord("a")] -= 1 + record[ord(i) - ord("a")] += 1 + for i in t: + record[ord(i) - ord("a")] -= 1 for i in range(26): if record[i] != 0: #record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。 @@ -154,6 +153,16 @@ class Solution: return s_dict == t_dict ``` +Python写法三(没有使用数组作为哈希表,只是介绍Counter这种更方便的解题思路): + +```python +class Solution(object): + def isAnagram(self, s: str, t: str) -> bool: + from collections import Counter + a_count = Counter(s) + b_count = Counter(t) + return a_count == b_count +``` Go: diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 47456455..56dbaa33 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -487,7 +487,34 @@ object Solution { .map(_._1) } } +``` +rust: 小根堆 + +```rust +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashMap}; +impl Solution { + pub fn top_k_frequent(nums: Vec, k: i32) -> Vec { + let mut hash = HashMap::new(); + let mut heap = BinaryHeap::with_capacity(k as usize); + nums.into_iter().for_each(|k| { + *hash.entry(k).or_insert(0) += 1; + }); + + for (k, v) in hash { + if heap.len() == heap.capacity() { + if *heap.peek().unwrap() < (Reverse(v), k) { + continue; + } else { + heap.pop(); + } + } + heap.push((Reverse(v), k)); + } + heap.into_iter().map(|(_, k)| k).collect() + } +} ```

diff --git a/problems/0583.两个字符串的删除操作.md b/problems/0583.两个字符串的删除操作.md index 6bc50421..ca3c118f 100644 --- a/problems/0583.两个字符串的删除操作.md +++ b/problems/0583.两个字符串的删除操作.md @@ -228,28 +228,43 @@ func min(a, b int) int { ``` Javascript: ```javascript -const minDistance = (word1, word2) => { - let dp = Array.from(new Array(word1.length + 1), () => Array(word2.length+1).fill(0)); - - for(let i = 1; i <= word1.length; i++) { - dp[i][0] = i; +// 方法一 +var minDistance = (word1, word2) => { + let dp = Array.from(new Array(word1.length + 1), () => + Array(word2.length + 1).fill(0) + ); + for (let i = 1; i <= word1.length; i++) { + dp[i][0] = i; + } + for (let j = 1; j <= word2.length; j++) { + dp[0][j] = j; + } + for (let i = 1; i <= word1.length; i++) { + for (let j = 1; j <= word2.length; 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] + 1, + dp[i][j - 1] + 1, + dp[i - 1][j - 1] + 2 + ); + } } + } + return dp[word1.length][word2.length]; +}; - for(let j = 1; j <= word2.length; j++) { - dp[0][j] = j; - } - - for(let i = 1; i <= word1.length; i++) { - for(let j = 1; j <= word2.length; 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] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + 2); - } - } - } - - return dp[word1.length][word2.length]; +// 方法二 +var minDistance = function (word1, word2) { + let dp = new Array(word1.length + 1) + .fill(0) + .map((_) => new Array(word2.length + 1).fill(0)); + for (let i = 1; i <= word1.length; i++) + for (let j = 1; j <= word2.length; 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 - 1][j], dp[i][j - 1]); + return word1.length + word2.length - dp[word1.length][word2.length] * 2; }; ``` diff --git a/problems/1254.统计封闭岛屿的数目.md b/problems/1254.统计封闭岛屿的数目.md index b70cd496..dc8fda41 100644 --- a/problems/1254.统计封闭岛屿的数目.md +++ b/problems/1254.统计封闭岛屿的数目.md @@ -76,8 +76,67 @@ public: return count; } }; +``` +## 其他语言版本 + +### JavaScript: + +```js +/** + * @param {number[][]} grid + * @return {number} + */ +var closedIsland = function(grid) { + let rows = grid.length; + let cols = grid[0].length; + // 存储四个方向 + let dir = [[-1, 0], [0, -1], [1, 0], [0, 1]]; + // 深度优先 + function dfs(x, y) { + grid[x][y] = 1; + // 向四个方向遍历 + for(let i = 0; i < 4; i++) { + let nextX = x + dir[i][0]; + let nextY = y + dir[i][1]; + // 判断是否越界 + if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols) continue; + // 不符合条件 + if (grid[nextX][nextY] === 1) continue; + // 继续递归 + dfs(nextX, nextY); + } + } + // 从边界岛屿开始 + // 从左侧和右侧出发 + for(let i = 0; i < rows; i++) { + if (grid[i][0] === 0) dfs(i, 0); + if (grid[i][cols - 1] === 0) dfs(i, cols - 1); + } + // 从上侧和下侧出发 + for(let j = 0; j < cols; j++) { + if (grid[0][j] === 0) dfs(0, j); + if (grid[rows - 1][j] === 0) dfs(rows - 1, j); + } + let count = 0; + // 排除所有与边界相连的陆地之后 + // 依次遍历网格中的每个元素,如果遇到一个元素是陆地且状态是未访问,则遇到一个新的岛屿,将封闭岛屿的数目加 1 + // 并访问与当前陆地连接的所有陆地 + for(let i = 0; i < rows; i++) { + for(let j = 0; j < cols; j++) { + if (grid[i][j] === 0) { + count++; + dfs(i, j); + } + } + } + return count; +}; ``` + +

+ + diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index e377626c..03422960 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -270,6 +270,29 @@ class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) var right: TreeNode = _right } ``` + +rust: + +```rust +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: T, + pub left: Option>>>, + pub right: Option>>>, +} + +impl TreeNode { + #[inline] + pub fn new(val: T) -> Self { + TreeNode { + val, + left: None, + right: None, + } + } +} +``` +

diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md index 030d3ae1..69c23e5c 100644 --- a/problems/二叉树的统一迭代法.md +++ b/problems/二叉树的统一迭代法.md @@ -666,6 +666,83 @@ object Solution { } } ``` + +rust: + +```rust +impl Solution{ + // 前序 + pub fn preorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + if root.is_some(){ + stack.push(root); + } + while !stack.is_empty(){ + if let Some(node) = stack.pop().unwrap(){ + if node.borrow().right.is_some(){ + stack.push(node.borrow().right.clone()); + } + if node.borrow().left.is_some(){ + stack.push(node.borrow().left.clone()); + } + stack.push(Some(node)); + stack.push(None); + }else{ + res.push(stack.pop().unwrap().unwrap().borrow().val); + } + } + res + } + // 中序 + pub fn inorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + if root.is_some() { + stack.push(root); + } + while !stack.is_empty() { + if let Some(node) = stack.pop().unwrap() { + if node.borrow().right.is_some() { + stack.push(node.borrow().right.clone()); + } + stack.push(Some(node.clone())); + stack.push(None); + if node.borrow().left.is_some() { + stack.push(node.borrow().left.clone()); + } + } else { + res.push(stack.pop().unwrap().unwrap().borrow().val); + } + } + res + } + // 后序 + pub fn postorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + if root.is_some() { + stack.push(root); + } + while !stack.is_empty() { + if let Some(node) = stack.pop().unwrap() { + stack.push(Some(node.clone())); + stack.push(None); + if node.borrow().right.is_some() { + stack.push(node.borrow().right.clone()); + } + if node.borrow().left.is_some() { + stack.push(node.borrow().left.clone()); + } + } else { + res.push(stack.pop().unwrap().unwrap().borrow().val); + } + } + res + } +} +``` +

diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index a20f11cb..2f67c323 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -640,6 +640,60 @@ object Solution { } } ``` + +rust: + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + //前序 + pub fn preorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![root]; + while !stack.is_empty() { + if let Some(node) = stack.pop().unwrap() { + res.push(node.borrow().val); + stack.push(node.borrow().right.clone()); + stack.push(node.borrow().left.clone()); + } + } + res + } + //中序 + pub fn inorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + let mut node = root; + + while !stack.is_empty() || node.is_some() { + while let Some(n) = node { + node = n.borrow().left.clone(); + stack.push(n); + } + if let Some(n) = stack.pop() { + res.push(n.borrow().val); + node = n.borrow().right.clone(); + } + } + res + } + //后序 + pub fn postorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![root]; + while !stack.is_empty() { + if let Some(node) = stack.pop().unwrap() { + res.push(node.borrow().val); + stack.push(node.borrow().left.clone()); + stack.push(node.borrow().right.clone()); + } + } + res.into_iter().rev().collect() + } +} +``` +

diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 03304caf..78861040 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -525,6 +525,46 @@ object Solution { } } ``` + +rust: + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn preorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + Self::traverse(&root, &mut res); + res + } + +//前序遍历 + pub fn traverse(root: &Option>>, res: &mut Vec) { + if let Some(node) = root { + res.push(node.borrow().val); + Self::traverse(&node.borrow().left, res); + Self::traverse(&node.borrow().right, res); + } + } +//后序遍历 + pub fn traverse(root: &Option>>, res: &mut Vec) { + if let Some(node) = root { + Self::traverse(&node.borrow().left, res); + Self::traverse(&node.borrow().right, res); + res.push(node.borrow().val); + } + } +//中序遍历 + pub fn traverse(root: &Option>>, res: &mut Vec) { + if let Some(node) = root { + Self::traverse(&node.borrow().left, res); + res.push(node.borrow().val); + Self::traverse(&node.borrow().right, res); + } + } +} +``` +