Merge branch 'youngyangyang04:master' into master

This commit is contained in:
roylx
2022-11-22 15:35:44 -07:00
committed by GitHub
10 changed files with 403 additions and 41 deletions

View File

@ -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]
```

View File

@ -754,23 +754,77 @@ 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
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
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

View File

@ -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

View File

@ -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<i32>, k: i32) -> Vec<i32> {
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()
}
}
```
<p align="center">

View File

@ -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;
};
```

View File

@ -77,7 +77,66 @@ public:
}
};
```
## 其他语言版本
### 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;
};
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -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<T> {
pub val: T,
pub left: Option<Rc<RefCell<TreeNode<T>>>>,
pub right: Option<Rc<RefCell<TreeNode<T>>>>,
}
impl<T> TreeNode<T> {
#[inline]
pub fn new(val: T) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

View File

@ -666,6 +666,83 @@ object Solution {
}
}
```
rust:
```rust
impl Solution{
// 前序
pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
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<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
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<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
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
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

View File

@ -640,6 +640,60 @@ object Solution {
}
}
```
rust:
```rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
//前序
pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
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<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
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<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
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()
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

View File

@ -525,6 +525,46 @@ object Solution {
}
}
```
rust:
```rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut res = vec![];
Self::traverse(&root, &mut res);
res
}
//前序遍历
pub fn traverse(root: &Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
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<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
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<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
Self::traverse(&node.borrow().left, res);
res.push(node.borrow().val);
Self::traverse(&node.borrow().right, res);
}
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>