Merge branch 'youngyangyang04:master' into master

This commit is contained in:
fw_qaq
2022-11-23 05:17:31 -05:00
committed by GitHub
8 changed files with 427 additions and 118 deletions

View File

@ -199,21 +199,15 @@ Python
```python3
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
if nums is None or len(nums)==0:
return 0
l=0
r=len(nums)-1
while l<r:
while(l<r and nums[l]!=val):
l+=1
while(l<r and nums[r]==val):
r-=1
nums[l], nums[r]=nums[r], nums[l]
print(nums)
if nums[l]==val:
return l
else:
return l+1
# 快指针遍历元素
fast = 0
# 慢指针记录位置
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow
```

View File

@ -271,6 +271,64 @@ class Solution {
}
```
```java
// 解法三
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = searchLeft(nums,target);
int right = searchRight(nums,target);
return new int[]{left,right};
}
public int searchLeft(int[] nums,int target){
// 寻找元素第一次出现的地方
int left = 0;
int right = nums.length-1;
while(left<=right){
int mid = left+(right-left)/2;
// >= 的都要缩小 因为要找第一个元素
if(nums[mid]>=target){
right = mid - 1;
}else{
left = mid + 1;
}
}
// right = left - 1
// 如果存在答案 right是首选
if(right>=0&&right<nums.length&&nums[right]==target){
return right;
}
if(left>=0&&left<nums.length&&nums[left]==target){
return left;
}
return -1;
}
public int searchRight(int[] nums,int target){
// 找最后一次出现
int left = 0;
int right = nums.length-1;
while(left<=right){
int mid = left + (right-left)/2;
// <= 的都要更新 因为我们要找最后一个元素
if(nums[mid]<=target){
left = mid + 1;
}else{
right = mid - 1;
}
}
// left = right + 1
// 要找最后一次出现 如果有答案 优先找left
if(left>=0&&left<nums.length&&nums[left]==target){
return left;
}
if(right>=0&&right<=nums.length&&nums[right]==target){
return right;
}
return -1;
}
}
```
### Python
@ -685,3 +743,4 @@ class Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

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

@ -380,29 +380,32 @@ object Solution {
Rust:
```rust
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
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());
}
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::VecDeque;
impl Solution {
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let mut res = vec![];
let mut queue = VecDeque::new();
if root.is_some() {
queue.push_back(root);
}
ans.push(level);
while !queue.is_empty() {
let mut temp = vec![];
for _ in 0..queue.len() {
let node = queue.pop_front().unwrap().unwrap();
temp.push(node.borrow().val);
if node.borrow().left.is_some() {
queue.push_back(node.borrow().left.clone());
}
if node.borrow().right.is_some() {
queue.push_back(node.borrow().right.clone());
}
}
res.push(temp);
}
res
}
ans
}
```
@ -665,29 +668,32 @@ object Solution {
Rust:
```rust
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
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());
}
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let mut res = vec![];
let mut queue = VecDeque::new();
if root.is_some() {
queue.push_back(root);
}
ans.push(level);
while !queue.is_empty() {
let mut temp = vec![];
for _ in 0..queue.len() {
let node = queue.pop_front().unwrap().unwrap();
temp.push(node.borrow().val);
if node.borrow().left.is_some() {
queue.push_back(node.borrow().left.clone());
}
if node.borrow().right.is_some() {
queue.push_back(node.borrow().right.clone());
}
}
res.push(temp);
}
res.into_iter().rev().collect()
}
ans
}
```
@ -935,6 +941,39 @@ object Solution {
}
```
rust:
```rust
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut res = vec![];
let mut queue = VecDeque::new();
if root.is_some() {
queue.push_back(root);
}
while !queue.is_empty() {
let len = queue.len();
for i in 0..len {
let node = queue.pop_front().unwrap().unwrap();
if i == len - 1 {
res.push(node.borrow().val);
}
if node.borrow().left.is_some() {
queue.push_back(node.borrow().left.clone());
}
if node.borrow().right.is_some() {
queue.push_back(node.borrow().right.clone());
}
}
}
res
}
}
```
# 637.二叉树的层平均值
[力扣题目链接](https://leetcode.cn/problems/average-of-levels-in-binary-tree/)
@ -1185,6 +1224,39 @@ object Solution {
}
```
rust:
```rust
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
let mut res = vec![];
let mut queue = VecDeque::new();
if root.is_some() {
queue.push_back(root);
}
while !queue.is_empty() {
let len = queue.len();
let mut sum = 0;
for _ in 0..len {
let node = queue.pop_front().unwrap().unwrap();
sum += node.borrow().val;
if node.borrow().left.is_some() {
queue.push_back(node.borrow().left.clone());
}
if node.borrow().right.is_some() {
queue.push_back(node.borrow().right.clone());
}
}
res.push((sum as f64) / len as f64);
}
res
}
}
```
# 429.N叉树的层序遍历
[力扣题目链接](https://leetcode.cn/problems/n-ary-tree-level-order-traversal/)
@ -1456,6 +1528,54 @@ object Solution {
}
```
rust:
```rust
pub struct Solution;
#[derive(Debug, PartialEq, Eq)]
pub struct Node {
pub val: i32,
pub children: Vec<Option<Rc<RefCell<Node>>>>,
}
impl Node {
#[inline]
pub fn new(val: i32) -> Node {
Node {
val,
children: vec![],
}
}
}
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn level_order(root: Option<Rc<RefCell<Node>>>) -> Vec<Vec<i32>> {
let mut res = vec![];
let mut queue = VecDeque::new();
if root.is_some() {
queue.push_back(root);
}
while !queue.is_empty() {
let mut temp = vec![];
for _ in 0..queue.len() {
let node = queue.pop_front().unwrap().unwrap();
temp.push(node.borrow().val);
if !node.borrow().children.is_empty() {
for n in node.borrow().children.clone() {
queue.push_back(n);
}
}
}
res.push(temp)
}
res
}
}
```
# 515.在每个树行中找最大值
[力扣题目链接](https://leetcode.cn/problems/find-largest-value-in-each-tree-row/)
@ -1686,6 +1806,38 @@ object Solution {
}
```
rust:
```rust
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn largest_values(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut res = vec![];
let mut queue = VecDeque::new();
if root.is_some() {
queue.push_back(root);
}
while !queue.is_empty() {
let mut max = i32::MIN;
for _ in 0..queue.len() {
let node = queue.pop_front().unwrap().unwrap();
max = max.max(node.borrow().val);
if node.borrow().left.is_some() {
queue.push_back(node.borrow().left.clone());
}
if node.borrow().right.is_some() {
queue.push_back(node.borrow().right.clone());
}
}
res.push(max);
}
res
}
}
```
# 116.填充每个节点的下一个右侧节点指针
[力扣题目链接](https://leetcode.cn/problems/populating-next-right-pointers-in-each-node/)
@ -2472,6 +2624,36 @@ object Solution {
}
```
rust:
```rust
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut queue = VecDeque::new();
let mut res = 0;
if root.is_some() {
queue.push_back(root);
}
while !queue.is_empty() {
res += 1;
for _ in 0..queue.len() {
let node = queue.pop_front().unwrap().unwrap();
if node.borrow().left.is_some() {
queue.push_back(node.borrow().left.clone());
}
if node.borrow().right.is_some() {
queue.push_back(node.borrow().right.clone());
}
}
}
res
}
}
```
# 111.二叉树的最小深度
[力扣题目链接](https://leetcode.cn/problems/minimum-depth-of-binary-tree/)
@ -2716,6 +2898,39 @@ object Solution {
}
```
rust:
```rust
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut res = 0;
let mut queue = VecDeque::new();
if root.is_some() {
queue.push_back(root);
}
while !queue.is_empty() {
res += 1;
for _ in 0..queue.len() {
let node = queue.pop_front().unwrap().unwrap();
if node.borrow().left.is_none() && node.borrow().right.is_none() {
return res;
}
if node.borrow().left.is_some() {
queue.push_back(node.borrow().left.clone());
}
if node.borrow().right.is_some() {
queue.push_back(node.borrow().right.clone());
}
}
}
res
}
}
```
# 总结
二叉树的层序遍历,**就是图论中的广度优先搜索在二叉树中的应用**,需要借助队列来实现(此时又发现队列的一个应用了)。

View File

@ -169,39 +169,18 @@ Python
```python
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
# 定义一个无限大的数
res = float("inf")
Sum = 0
index = 0
for i in range(len(nums)):
Sum += nums[i]
res = float("inf") # 定义一个无限大的数
Sum = 0 # 滑动窗口数值之和
i = 0 # 滑动窗口起始位置
for j in range(len(nums)):
Sum += nums[j]
while Sum >= s:
res = min(res, i-index+1)
Sum -= nums[index]
index += 1
return 0 if res==float("inf") else res
```
```python
# 滑动窗口
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
if nums is None or len(nums) == 0:
return 0
lenf = len(nums) + 1
total = 0
i = j = 0
while (j < len(nums)):
total = total + nums[j]
j += 1
while (total >= target):
lenf = min(lenf, j - i)
total = total - nums[i]
res = min(res, j-i+1)
Sum -= nums[i]
i += 1
if lenf == len(nums) + 1:
return 0
else:
return lenf
return 0 if res == float("inf") else res
```
Go
```go
func minSubArrayLen(target int, nums []int) int {
@ -232,22 +211,23 @@ func minSubArrayLen(target int, nums []int) int {
JavaScript:
```js
var minSubArrayLen = function(target, nums) {
// 长度计算一次
const len = nums.length;
let l = r = sum = 0,
res = len + 1; // 子数组最大不会超过自身
while(r < len) {
sum += nums[r++];
// 窗口滑动
while(sum >= target) {
// r始终为开区间 [l, r)
res = res < r - l ? res : r - l;
sum-=nums[l++];
let start, end
start = end = 0
let sum = 0
let len = nums.length
let ans = Infinity
while(end < len){
sum += nums[end];
while (sum >= target) {
ans = Math.min(ans, end - start + 1);
sum -= nums[start];
start++;
}
end++;
}
return res > len ? 0 : res;
return ans === Infinity ? 0 : ans
};
```

View File

@ -108,9 +108,12 @@ public:
// 如果index大于链表的长度则返回空
// 如果index小于0则置为0作为链表的新头节点。
void addAtIndex(int index, int val) {
if (index > _size || index < 0) {
if (index > _size) {
return;
}
if (index < 0) {
index = 0;
}
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = _dummyHead;
while(index--) {

View File

@ -9,7 +9,7 @@
什么是链表链表是一种通过指针串联在一起的线性结构每一个节点由两部分组成一个是数据域一个是指针域存放指向下一个节点的指针最后一个节点的指针域指向null空指针的意思
的入口节点称为链表的头结点也就是head。
的入口节点称为链表的头结点也就是head。
如图所示:
![链表1](https://img-blog.csdnimg.cn/20200806194529815.png)