From 7d11733da7c396e96abebf6bf8e5debc8d1e1300 Mon Sep 17 00:00:00 2001 From: wang2jun <91008685+wang2jun@users.noreply.github.com> Date: Sat, 29 Oct 2022 14:17:54 +0800 Subject: [PATCH 01/62] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20841=E9=92=A5?= =?UTF-8?q?=E5=8C=99=E5=92=8C=E6=88=BF=E9=97=B4=20TS=20=EF=BC=88BFS?= =?UTF-8?q?=EF=BC=89=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 841钥匙和房间 TS (BFS) 代码 --- problems/0841.钥匙和房间.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0841.钥匙和房间.md b/problems/0841.钥匙和房间.md index 0233a710..5556922c 100644 --- a/problems/0841.钥匙和房间.md +++ b/problems/0841.钥匙和房间.md @@ -387,6 +387,34 @@ var canVisitAllRooms = function(rooms) { ``` +### TypeScript +```ts +// BFS +// rooms :就是一个链接表 表示的有向图 +// 转换问题就是,一次遍历从 0开始 能不能 把所有的节点访问了,实质问题就是一个 +// 层序遍历 +function canVisitAllRooms(rooms: number[][]): boolean { + const n = rooms.length; + // cnt[i] 代表节点 i 的访问顺序, cnt[i] = 0, 代表没被访问过 + let cnt = new Array(n).fill(0); + let queue = [0]; + cnt[0]++; + while (queue.length > 0) { + const from = queue.shift(); + for (let i = 0; i < rooms[from].length; i++) { + const to = rooms[from][i]; + if (cnt[to] == 0) { + queue.push(to); + cnt[to]++; + } + } + } + // 只要其中有一个节点 没被访问过,那么就返回 false + return cnt.every((item) => item != 0); +} +``` + +

From 67a84f74c134a519c4681e00f89fe9f0663c66d3 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 29 Oct 2022 18:17:20 +0800 Subject: [PATCH 02/62] =?UTF-8?q?update=200232.=E7=94=A8=E6=A0=88=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E9=98=9F=E5=88=97.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0232.用栈实现队列.md | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 1ed0c5d6..e6a58be3 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -622,6 +622,48 @@ class MyQueue() { } ``` +rust: + +```rust +struct MyQueue { + stack_in: Vec, + stack_out: Vec, +} +impl MyQueue { + + fn new() -> Self { + MyQueue { + stack_in: Vec::new(), + stack_out: Vec::new(), + } + + } + + fn push(&mut self, x: i32) { + self.stack_in.push(x); + } + + fn pop(&mut self) -> i32 { + if self.stack_out.is_empty(){ + while !self.stack_in.is_empty() { + self.stack_out.push(self.stack_in.pop().unwrap()); + } + } + self.stack_out.pop().unwrap() + } + + fn peek(&mut self) -> i32 { + let res = self.pop(); + self.stack_out.push(res); + res + } + + fn empty(&self) -> bool { + self.stack_in.is_empty() && self.stack_out.is_empty() + } +} +``` +

From 7950be58a29b0757189d3afdb25ccf45e1bbf2a6 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 29 Oct 2022 18:18:34 +0800 Subject: [PATCH 03/62] =?UTF-8?q?Update=200232.=E7=94=A8=E6=A0=88=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E9=98=9F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0232.用栈实现队列.md | 1 - 1 file changed, 1 deletion(-) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index e6a58be3..5858f9e0 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -630,7 +630,6 @@ struct MyQueue { stack_out: Vec, } impl MyQueue { - fn new() -> Self { MyQueue { stack_in: Vec::new(), From 9769fefe0f4305eabbf275d2db61e8cdd2871c31 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 29 Oct 2022 18:47:41 +0800 Subject: [PATCH 04/62] =?UTF-8?q?update=200225.=E7=94=A8=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=A0=88.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0225.用队列实现栈.md | 40 ++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 9aa8d8a1..2f015272 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -1018,7 +1018,7 @@ class MyStack { } } ``` -> 单对列 +> 单队列 ```php class MyStack { public $queue; @@ -1051,6 +1051,44 @@ class MyStack { } } ``` + +> rust:单队列 + +```rust +struct MyStack { + queue: Vec, +} + +impl MyStack { + fn new() -> Self { + MyStack { queue: vec![] } + } + + fn push(&mut self, x: i32) { + self.queue.push(x); + } + + fn pop(&mut self) -> i32 { + let len = self.queue.len() - 1; + for _ in 0..len { + let tmp = self.queue.remove(0); + self.queue.push(tmp); + } + self.queue.remove(0) + } + + fn top(&mut self) -> i32 { + let res = self.pop(); + self.queue.push(res); + res + } + + fn empty(&self) -> bool { + self.queue.is_empty() + } +} +``` +

From 2df651a1358066246a72f3697dd04407628261d8 Mon Sep 17 00:00:00 2001 From: asiL-tcefreP <1626680964@qq.com> Date: Sat, 29 Oct 2022 13:54:57 -0400 Subject: [PATCH 05/62] =?UTF-8?q?Update=200084.=E6=9F=B1=E7=8A=B6=E5=9B=BE?= =?UTF-8?q?=E4=B8=AD=E6=9C=80=E5=A4=A7=E7=9A=84=E7=9F=A9=E5=BD=A2.md=20(Ja?= =?UTF-8?q?va=E7=89=88=E6=9C=AC)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0084.柱状图中最大的矩形.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/problems/0084.柱状图中最大的矩形.md b/problems/0084.柱状图中最大的矩形.md index 220b096e..bcb0915e 100644 --- a/problems/0084.柱状图中最大的矩形.md +++ b/problems/0084.柱状图中最大的矩形.md @@ -206,7 +206,7 @@ class Solution { public int largestRectangleArea(int[] heights) { int length = heights.length; int[] minLeftIndex = new int [length]; - int[] maxRigthIndex = new int [length]; + int[] minRightIndex = new int [length]; // 记录左边第一个小于该柱子的下标 minLeftIndex[0] = -1 ; for (int i = 1; i < length; i++) { @@ -215,17 +215,17 @@ class Solution { while (t >= 0 && heights[t] >= heights[i]) t = minLeftIndex[t]; minLeftIndex[i] = t; } - // 记录每个柱子 右边第一个小于该柱子的下标 - maxRigthIndex[length - 1] = length; + // 记录每个柱子右边第一个小于该柱子的下标 + minRightIndex[length - 1] = length; for (int i = length - 2; i >= 0; i--) { int t = i + 1; - while(t < length && heights[t] >= heights[i]) t = maxRigthIndex[t]; - maxRigthIndex[i] = t; + while(t < length && heights[t] >= heights[i]) t = minRightIndex[t]; + minRightIndex[i] = t; } // 求和 int result = 0; for (int i = 0; i < length; i++) { - int sum = heights[i] * (maxRigthIndex[i] - minLeftIndex[i] - 1); + int sum = heights[i] * (minRightIndex[i] - minLeftIndex[i] - 1); result = Math.max(sum, result); } return result; From 2e5466bdce0a3d884a1a9084da74732a80fe806d Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 31 Oct 2022 10:41:54 +0800 Subject: [PATCH 06/62] =?UTF-8?q?update=200020.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E6=8B=AC=E5=8F=B7.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0020.有效的括号.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 3d986a82..69713c62 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -493,6 +493,33 @@ object Solution { } ``` +rust: + +```rust +impl Solution { + pub fn is_valid(s: String) -> bool { + if s.len() % 2 == 1 { + return false; + } + let mut stack = vec![]; + let mut chars: Vec = s.chars().collect(); + while let Some(s) = chars.pop() { + match s { + ')' => stack.push('('), + ']' => stack.push('['), + '}' => stack.push('{'), + _ => { + if stack.is_empty() || stack.pop().unwrap() != s { + return false; + } + } + } + } + stack.is_empty() + } +} +``` +

From 309b49cf47699554a928354e2621575ec524db2f Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 31 Oct 2022 10:59:59 +0800 Subject: [PATCH 07/62] =?UTF-8?q?update=201047.=E5=88=A0=E9=99=A4=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=9A=84=E6=89=80=E6=9C=89=E7=9B=B8?= =?UTF-8?q?=E9=82=BB=E9=87=8D=E5=A4=8D=E9=A1=B9.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1047.删除字符串中的所有相邻重复项.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 849b5e79..ad729298 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -447,6 +447,25 @@ object Solution { } ``` +rust: + +```rust +impl Solution { + pub fn remove_duplicates(s: String) -> String { + let mut stack = vec![]; + let mut chars: Vec = s.chars().collect(); + while let Some(c) = chars.pop() { + if stack.is_empty() || stack[stack.len() - 1] != c { + stack.push(c); + } else { + stack.pop(); + } + } + stack.into_iter().rev().collect() + } +} +``` +

From 3db9b494f9c433b2c8e9c350200a3ca877788865 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 31 Oct 2022 11:53:08 +0800 Subject: [PATCH 08/62] =?UTF-8?q?update=200150.=E9=80=86=E6=B3=A2=E5=85=B0?= =?UTF-8?q?=E8=A1=A8=E8=BE=BE=E5=BC=8F=E6=B1=82=E5=80=BC.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0150.逆波兰表达式求值.md | 39 +++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index 108c654b..78dfae3e 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -89,12 +89,8 @@ C++代码如下: class Solution { public: int evalRPN(vector& tokens) { -<<<<<<< HEAD - stack st; -======= // 力扣修改了后台测试数据,需要用longlong stack st; ->>>>>>> 28f3b52a82e3cc650290fb02030a53900e122f43 for (int i = 0; i < tokens.size(); i++) { if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") { long long num1 = st.top(); @@ -424,6 +420,41 @@ object Solution { } ``` + +rust: + +```rust +impl Solution { + pub fn eval_rpn(tokens: Vec) -> i32 { + let mut stack = vec![]; + for token in tokens.into_iter() { + match token.as_str() { + "+" => { + let a = stack.pop().unwrap(); + *stack.last_mut().unwrap() += a; + } + "-" => { + let a = stack.pop().unwrap(); + *stack.last_mut().unwrap() -= a; + } + "*" => { + let a = stack.pop().unwrap(); + *stack.last_mut().unwrap() *= a; + } + "/" => { + let a = stack.pop().unwrap(); + *stack.last_mut().unwrap() /= a; + } + _ => { + stack.push(token.parse::().unwrap()); + } + } + } + stack.pop().unwrap() + } +} +``` +

From 5b3b774083e5e204bd777652d6eb2452d83f06c4 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 31 Oct 2022 13:10:25 +0800 Subject: [PATCH 09/62] =?UTF-8?q?update=200239.=E6=BB=91=E5=8A=A8=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 2d556d8b..40da879c 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -802,6 +802,35 @@ class myDequeue{ } ``` +rust: + +```rust +impl Solution { + pub fn max_sliding_window(nums: Vec, k: i32) -> Vec { + let mut res = vec![]; + let mut queue = VecDeque::with_capacity(k as usize); + for (i, &v) in nums.iter().enumerate() { + // 如果队列长度超过 k,那么需要移除队首过期元素 + if i - queue.front().unwrap_or(&0) == k as usize { + queue.pop_front(); + } + while let Some(&index) = queue.back() { + if nums[index] >= v { + break; + } + // 如果队列第一个元素比当前元素小,那么就把队列第一个元素弹出 + queue.pop_back(); + } + queue.push_back(i); + if i >= k as usize - 1 { + res.push(nums[queue[0]]); + } + } + res + } +} +``` +

From 31fa56d22947167a37ad767134ea98055314f367 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 31 Oct 2022 17:48:33 +0800 Subject: [PATCH 10/62] =?UTF-8?q?0347.=E5=89=8DK=E4=B8=AA=E9=AB=98?= =?UTF-8?q?=E9=A2=91=E5=85=83=E7=B4=A0.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) 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() + } +} ```

From 7803388377332c18559fa19296b064aa076a1f1b Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 5 Nov 2022 14:30:53 +0800 Subject: [PATCH 11/62] =?UTF-8?q?update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树理论基础.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index e377626c..d520273a 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: i32, + pub left: Option>>, + pub right: Option>>, +} + +impl TreeNode { + #[inline] + pub fn new(val: i32) -> Self { + TreeNode { + val, + left: None, + right: None, + } + } +} +``` +

From 72b6043daa4956cf6d0045e279792f1c35dd78b7 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 5 Nov 2022 14:36:15 +0800 Subject: [PATCH 12/62] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树理论基础.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index d520273a..03422960 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -275,15 +275,15 @@ rust: ```rust #[derive(Debug, PartialEq, Eq)] -pub struct TreeNode { - pub val: i32, - pub left: Option>>, - pub right: Option>>, +pub struct TreeNode { + pub val: T, + pub left: Option>>>, + pub right: Option>>>, } -impl TreeNode { +impl TreeNode { #[inline] - pub fn new(val: i32) -> Self { + pub fn new(val: T) -> Self { TreeNode { val, left: None, From c64c013b9b157b99ac6a87308a2e4352abbd989f Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 5 Nov 2022 16:24:41 +0800 Subject: [PATCH 13/62] =?UTF-8?q?update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) 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); + } + } +} +``` +

From 51d8be645aab9f15101c759535785492c4162e58 Mon Sep 17 00:00:00 2001 From: Zeeland <287017217@qq.com> Date: Sat, 5 Nov 2022 18:08:43 +0800 Subject: [PATCH 14/62] =?UTF-8?q?Update=200242.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 删除一行不必要的print,简化for循环代码 --- problems/0242.有效的字母异位词.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index f8ebc545..b7100b52 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 一定是谁多了字符或者谁少了字符。 From 7f53e73e544dd650bc7c8efb321fbaafe775fbe3 Mon Sep 17 00:00:00 2001 From: Zeeland <287017217@qq.com> Date: Sat, 5 Nov 2022 18:22:51 +0800 Subject: [PATCH 15/62] =?UTF-8?q?Update=200242.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加新的python题解方法 --- problems/0242.有效的字母异位词.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index f8ebc545..93ab90a2 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -154,6 +154,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: From 4ecf4714c71f2ca6ea3179a161beec76adfc118b Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 7 Nov 2022 00:08:02 +0800 Subject: [PATCH 16/62] =?UTF-8?q?update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E8=BF=AD=E4=BB=A3=E9=81=8D=E5=8E=86.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的迭代遍历.md | 54 ++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) 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() + } +} +``` +

From 1e40f295a9906df7b5c4308cb1fe733e73bf02b4 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 7 Nov 2022 17:24:44 +0800 Subject: [PATCH 17/62] =?UTF-8?q?update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E7=BB=9F=E4=B8=80=E8=BF=AD=E4=BB=A3=E6=B3=95.md=20abo?= =?UTF-8?q?ut=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的统一迭代法.md | 77 ++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md index 030d3ae1..6e768ec7 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 + } +} +``` +

From 24d7ad68f0a906fac3c7d27e6db6d7116f89e40f Mon Sep 17 00:00:00 2001 From: wantsnowfly <2856628706@qq.com> Date: Mon, 7 Nov 2022 17:56:01 +0800 Subject: [PATCH 18/62] =?UTF-8?q?=E5=A2=9E=E5=8A=A0034=20java=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...排序数组中查找元素的第一个和最后一个位置.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md index dc6833f6..c7ff6dce 100644 --- a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md +++ b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md @@ -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=0&&left=0&&left=0&&right<=nums.length&&nums[right]==target){ + return right; + } + return -1; + } +} +``` + ### Python @@ -685,3 +743,4 @@ class Solution { + From 3f70c16fa6bbb059cd7e102b791d25b844bafd74 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 8 Nov 2022 01:29:42 +0800 Subject: [PATCH 19/62] =?UTF-8?q?update=200102.=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.md=20about=20usin?= =?UTF-8?q?g=20vecdeque=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 45 ++++++++++++++++--------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 3a4e0a31..f4f51f01 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -380,29 +380,32 @@ object Solution { 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()); - } +use std::cell::RefCell; +use std::rc::Rc; +use std::collections::VecDeque; +impl Solution { + pub fn level_order(root: Option>>) -> Vec> { + 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 } ``` From 38b5d05390d117cc77aba0a3026846bed32d75cd Mon Sep 17 00:00:00 2001 From: Hongfei Duan <1715106673@qq.com> Date: Tue, 8 Nov 2022 11:20:26 +0800 Subject: [PATCH 20/62] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=201254=E7=BB=9F?= =?UTF-8?q?=E8=AE=A1=E5=B0=81=E9=97=AD=E5=B2=9B=E5=B1=BF=E7=9A=84=E6=95=B0?= =?UTF-8?q?=E7=9B=AE=20js=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1254.统计封闭岛屿的数目.md | 56 +++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/problems/1254.统计封闭岛屿的数目.md b/problems/1254.统计封闭岛屿的数目.md index b70cd496..1270085a 100644 --- a/problems/1254.统计封闭岛屿的数目.md +++ b/problems/1254.统计封闭岛屿的数目.md @@ -81,3 +81,59 @@ 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; +}; +``` From fe46bb43d2272c656c0744b88081b72487276798 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 8 Nov 2022 12:51:43 +0800 Subject: [PATCH 21/62] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E7=BB=9F=E4=B8=80=E8=BF=AD=E4=BB=A3=E6=B3=95.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的统一迭代法.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md index 6e768ec7..69c23e5c 100644 --- a/problems/二叉树的统一迭代法.md +++ b/problems/二叉树的统一迭代法.md @@ -695,7 +695,7 @@ impl Solution{ res } // 中序 - pub fn inorder_traversal(root: Option>>) -> Vec { + pub fn inorder_traversal(root: Option>>) -> Vec { let mut res = vec![]; let mut stack = vec![]; if root.is_some() { From d5392f4936b412e0b288d5170254b3f6aa12f15e Mon Sep 17 00:00:00 2001 From: wang2jun <91008685+wang2jun@users.noreply.github.com> Date: Tue, 8 Nov 2022 15:01:42 +0800 Subject: [PATCH 22/62] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200583=20=E4=B8=A4?= =?UTF-8?q?=E4=B8=AA=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=9A=84=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=20Javascript=20=E6=96=B9=E6=B3=95=E4=BA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加 0583 两个字符串的删除操作 Javascript 方法二 --- problems/0583.两个字符串的删除操作.md | 55 +++++++++++++++++---------- 1 file changed, 35 insertions(+), 20 deletions(-) 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; }; ``` From f7730fad4b3a955f6e5d031cbf2c769bbe42a228 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 8 Nov 2022 18:29:56 +0800 Subject: [PATCH 23/62] =?UTF-8?q?Update=200102.=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.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 45 ++++++++++++++++--------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index f4f51f01..e6e8f210 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -668,29 +668,32 @@ object Solution { 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()); - } +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; +impl Solution { + pub fn level_order_bottom(root: Option>>) -> Vec> { + 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 } ``` From 0b060140d649cd984733e6becdc9feb560a890aa Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 8 Nov 2022 18:55:36 +0800 Subject: [PATCH 24/62] =?UTF-8?q?Update=200102.=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.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index e6e8f210..c9a6b476 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -941,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>>) -> Vec { + 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/) From 012081f38f78465ec6994db3cf035345384ab82b Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 8 Nov 2022 20:46:44 +0800 Subject: [PATCH 25/62] =?UTF-8?q?Update=200102.=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.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index c9a6b476..6cb4b5e3 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1224,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>>) -> Vec { + 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/) From 07d365dcc5ecf862d639eaf9d747cc5f0a9c283b Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 8 Nov 2022 21:34:54 +0800 Subject: [PATCH 26/62] =?UTF-8?q?Update=200102.=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.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 6cb4b5e3..e75455f3 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1758,6 +1758,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>>) -> Vec { + 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/) From ece7623da2873f1c0c0ec31e037daf7d1b38162b Mon Sep 17 00:00:00 2001 From: lihuacai Date: Wed, 9 Nov 2022 02:22:43 +0800 Subject: [PATCH 27/62] =?UTF-8?q?feat:=20update=5F63=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E8=B7=AF=E5=BE=84II=5Fpython3,=20=E5=8F=8D=E5=90=91=E5=88=A4?= =?UTF-8?q?=E6=96=AD=E6=94=B9=E6=88=90=E6=AD=A3=E5=90=91=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0063.不同路径II.md | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) 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] ``` From 30550b06af1810bf6bab063cce1b3b31da0e2396 Mon Sep 17 00:00:00 2001 From: Jijie LIU Date: Tue, 8 Nov 2022 21:50:00 +0100 Subject: [PATCH 28/62] =?UTF-8?q?Update=200101.=E5=AF=B9=E7=A7=B0=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 66 +++++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 6 deletions(-) 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 + } +} +```

From ef5b014228c2f0002637b4af0a279596a2b53a60 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Wed, 9 Nov 2022 23:19:00 +0800 Subject: [PATCH 29/62] =?UTF-8?q?Update=200102.=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.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index e75455f3..f1ec3918 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2576,6 +2576,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>>) -> 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/) From 0797680df421740987c05ca5f5d3501794b53a31 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Wed, 9 Nov 2022 23:30:55 +0800 Subject: [PATCH 30/62] =?UTF-8?q?Update=200102.=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.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index f1ec3918..acd91c6b 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2850,6 +2850,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>>) -> 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 + } +} +``` + # 总结 二叉树的层序遍历,**就是图论中的广度优先搜索在二叉树中的应用**,需要借助队列来实现(此时又发现队列的一个应用了)。 From 75103a887219ca10080a5cdb8ef4639bfe46422c Mon Sep 17 00:00:00 2001 From: xu <44153643+xu-kai-xu@users.noreply.github.com> Date: Thu, 10 Nov 2022 19:29:01 +0800 Subject: [PATCH 31/62] =?UTF-8?q?Update=20=E9=93=BE=E8=A1=A8=E7=90=86?= =?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=80.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 链表理论基础,一处可能的文字错误。 --- problems/链表理论基础.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/链表理论基础.md b/problems/链表理论基础.md index cdd861fd..a0b13f89 100644 --- a/problems/链表理论基础.md +++ b/problems/链表理论基础.md @@ -9,7 +9,7 @@ 什么是链表,链表是一种通过指针串联在一起的线性结构,每一个节点由两部分组成,一个是数据域一个是指针域(存放指向下一个节点的指针),最后一个节点的指针域指向null(空指针的意思)。 -链接的入口节点称为链表的头结点也就是head。 +链表的入口节点称为链表的头结点也就是head。 如图所示: ![链表1](https://img-blog.csdnimg.cn/20200806194529815.png) From a2e84d93d9103298e7c11c4042ee1352da71877b Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Thu, 10 Nov 2022 22:05:42 +0800 Subject: [PATCH 32/62] =?UTF-8?q?leetcode=20=E8=BF=98=E6=B2=A1=E6=9C=89?= =?UTF-8?q?=E9=A2=98=EF=BC=8C=E8=87=AA=E5=B7=B1=E6=9E=84=E5=BB=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index acd91c6b..1a01c0ae 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1528,6 +1528,54 @@ object Solution { } ``` +rust: + +```rust +pub struct Solution; +#[derive(Debug, PartialEq, Eq)] +pub struct Node { + pub val: i32, + pub children: Vec>>>, +} + +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>>) -> Vec> { + 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/) From bec57550df7a01fccb7fe060ce569e499285a134 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Thu, 10 Nov 2022 17:27:45 -0700 Subject: [PATCH 33/62] =?UTF-8?q?Update=200376.=E6=91=86=E5=8A=A8=E5=BA=8F?= =?UTF-8?q?=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加python动态规划优化版 --- problems/0376.摆动序列.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 214ff311..f9d3f97f 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -264,6 +264,25 @@ class Solution: return max(dp[-1][0], dp[-1][1]) ``` +```python +class Solution: + def wiggleMaxLength(self, nums: List[int]) -> int: + # up i作为波峰最长的序列长度 + # down i作为波谷最长的序列长度 + n = len(nums) + # 长度为0和1的直接返回长度 + if n<2: return n + for i in range(1,n): + if nums[i]>nums[i-1]: + # nums[i] 为波峰,1. 前面是波峰,up值不变,2. 前面是波谷,down值加1 + # 目前up值取两者的较大值(其实down+1即可,可以推理前一步down和up最多相差1,所以down+1>=up) + up = max(up, down+1) + elif nums[i] Date: Sun, 13 Nov 2022 10:42:00 +0800 Subject: [PATCH 34/62] =?UTF-8?q?=E5=8F=8D=E8=BD=AC=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2Java=E5=85=B6=E4=BB=96=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0344.反转字符串.md | 18 ++++++++++++++++++ problems/0541.反转字符串II.md | 24 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index f5b0e22b..2807d04a 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -151,6 +151,23 @@ class Solution { } } } + +// 第二种方法用temp来交换数值更多人容易理解些 +class Solution { + public void reverseString(char[] s) { + int l = 0; + int r = s.length - 1; + while(l < r){ + char temp = s[l]; + s[l] = s[r]; + s[r] = temp; + l++; + r--; + } + } +} + + ``` Python: @@ -335,3 +352,4 @@ object Solution { + diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 238e6349..59891365 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -194,6 +194,29 @@ class Solution { return new String(ch); } } + + +// 解法二还可以用temp来交换数值,会的人更多些 +class Solution { + public String reverseStr(String s, int k) { + char[] ch = s.toCharArray(); + for(int i = 0;i < ch.length;i += 2 * k){ + int start = i; + // 判断尾数够不够k个来取决end指针的位置 + int end = Math.min(ch.length - 1,start + k - 1); + while(start < end){ + + char temp = ch[start]; + ch[start] = ch[end]; + ch[end] = temp; + + start++; + end--; + } + } + return new String(ch); + } +} ``` ```java // 解法3 @@ -469,3 +492,4 @@ impl Solution { + From 9d0872312c211f877e7af9dc2e76302961fd46af Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 13 Nov 2022 16:16:48 +0800 Subject: [PATCH 35/62] =?UTF-8?q?Update=200226.=E7=BF=BB=E8=BD=AC=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 9c34ce20..3136c0be 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -857,6 +857,36 @@ object Solution { } ``` +### rust + +```rust +impl Solution { + //* 递归 */ + pub fn invert_tree(root: Option>>) -> Option>> { + if let Some(node) = root.as_ref() { + let (left, right) = (node.borrow().left.clone(), node.borrow().right.clone()); + node.borrow_mut().left = Self::invert_tree(right); + node.borrow_mut().right = Self::invert_tree(left); + } + root + } + //* 迭代 */ + pub fn invert_tree(root: Option>>) -> Option>> { + let mut stack = vec![root.clone()]; + while !stack.is_empty() { + if let Some(node) = stack.pop().unwrap() { + let (left, right) = (node.borrow().left.clone(), node.borrow().right.clone()); + stack.push(right.clone()); + stack.push(left.clone()); + node.borrow_mut().left = right; + node.borrow_mut().right = left; + } + } + root + } +} +``` +

From 7c97e9b7d29345e12d16bd34e04233bc78e16ff8 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 13 Nov 2022 17:43:14 +0800 Subject: [PATCH 36/62] =?UTF-8?q?Update=200101.=E5=AF=B9=E7=A7=B0=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 30ca3d77..6c96f1db 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -772,6 +772,34 @@ object Solution { } ``` +## Rust + +递归: +```rust +impl Solution { + pub fn is_symmetric(root: Option>>) -> bool { + Self::recur( + &root.as_ref().unwrap().borrow().left, + &root.as_ref().unwrap().borrow().right, + ) + } + pub fn recur( + left: &Option>>, + right: &Option>>, + ) -> bool { + match (left, right) { + (None, None) => true, + (Some(n1), Some(n2)) => { + return n1.borrow().val == n2.borrow().val + && Self::recur(&n1.borrow().left, &n2.borrow().right) + && Self::recur(&n1.borrow().right, &n2.borrow().left) + } + _ => false, + } + } +} +``` +

From 30a7d36699fcf7f7ffada9b3381553c7e3924873 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 13 Nov 2022 18:36:39 +0800 Subject: [PATCH 37/62] =?UTF-8?q?Update=200101.=E5=AF=B9=E7=A7=B0=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 6c96f1db..841dbec3 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -800,6 +800,39 @@ impl Solution { } ``` +迭代: +```rust +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; +impl Solution { + pub fn is_symmetric(root: Option>>) -> bool { + let mut queue = VecDeque::new(); + if let Some(node) = root { + queue.push_back(node.borrow().left.clone()); + queue.push_back(node.borrow().right.clone()); + } + while !queue.is_empty() { + let (n1, n2) = (queue.pop_front().unwrap(), queue.pop_front().unwrap()); + match (n1.clone(), n2.clone()) { + (None, None) => continue, + (Some(n1), Some(n2)) => { + if n1.borrow().val != n2.borrow().val { + return false; + } + } + _ => return false, + }; + queue.push_back(n1.as_ref().unwrap().borrow().left.clone()); + queue.push_back(n2.as_ref().unwrap().borrow().right.clone()); + queue.push_back(n1.unwrap().borrow().right.clone()); + queue.push_back(n2.unwrap().borrow().left.clone()); + } + true + } +} +``` +

From 875680c44c216bd3e63d87133d0a108f09f8b661 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 13 Nov 2022 19:35:09 +0800 Subject: [PATCH 38/62] =?UTF-8?q?Update=200104.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 70 +++++++++++++++++++------------ 1 file changed, 44 insertions(+), 26 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index be53c417..ee7bd50e 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -200,32 +200,6 @@ 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叉树的最大深度问题 @@ -975,6 +949,50 @@ object Solution { } ``` +## rust +### 0104.二叉树的最大深度 + +递归: +```rust +impl Solution { + pub fn max_depth(root: Option>>) -> i32 { + if root.is_none() { + return 0; + } + std::cmp::max( + Self::max_depth(root.clone().unwrap().borrow().left.clone()), + Self::max_depth(root.unwrap().borrow().right.clone()), + ) + 1 + } +} +``` + +迭代: +```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 + } +``` +

From ed2588520a9e6822e110995baa34c7d278c26204 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Mon, 14 Nov 2022 15:00:07 -0700 Subject: [PATCH 39/62] =?UTF-8?q?Update=200121.=E4=B9=B0=E5=8D=96=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加了python 动态规划:版本三 --- problems/0121.买卖股票的最佳时机.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index 63ac5d04..cf17f48d 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -310,6 +310,18 @@ class Solution: return dp[(length-1) % 2][1] ``` +> 动态规划:版本三 +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + length = len(prices) + dp0, dp1 = -prices[0], 0 #注意这里只维护两个常量,因为dp0的更新不受dp1的影响 + for i in range(1, length): + dp1 = max(dp1, dp0 + prices[i]) + dp0 = max(dp0, -prices[i]) + return dp1 +``` + Go: > 贪心法: ```Go From 4261d96a144c91ba577a1a2c3bdad5fb7ce38696 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Tue, 15 Nov 2022 10:27:03 -0700 Subject: [PATCH 40/62] =?UTF-8?q?Update=200714.=E4=B9=B0=E5=8D=96=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA=E5=90=AB?= =?UTF-8?q?=E6=89=8B=E7=BB=AD=E8=B4=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新Python贪心,更容易理解 --- problems/0714.买卖股票的最佳时机含手续费.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/problems/0714.买卖股票的最佳时机含手续费.md b/problems/0714.买卖股票的最佳时机含手续费.md index 66fb9fb6..faa56d42 100644 --- a/problems/0714.买卖股票的最佳时机含手续费.md +++ b/problems/0714.买卖股票的最佳时机含手续费.md @@ -206,13 +206,13 @@ class Solution: # 贪心思路 result = 0 minPrice = prices[0] for i in range(1, len(prices)): - if prices[i] < minPrice: + if prices[i] < minPrice: # 此时有更低的价格,可以买入 minPrice = prices[i] - elif prices[i] >= minPrice and prices[i] <= minPrice + fee: - continue - else: - result += prices[i] - minPrice - fee + elif prices[i] > (minPrice + fee): # 此时有利润,同时假买入高价的股票,看看是否继续盈利 + result += prices[i] - (minPrice + fee) minPrice = prices[i] - fee + else: # minPrice<= prices[i] <= minPrice + fee, 价格处于minPrice和minPrice+fee之间,不做操作 + continue return result ``` From 6fb61ead0b5d723775958827e4d75a7199aecfe6 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Tue, 15 Nov 2022 11:01:24 -0700 Subject: [PATCH 41/62] =?UTF-8?q?Update=200055.=E8=B7=B3=E8=B7=83=E6=B8=B8?= =?UTF-8?q?=E6=88=8F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加Python for循环版 --- problems/0055.跳跃游戏.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index 23357f21..0ed03b07 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -119,6 +119,18 @@ class Solution: return False ``` +```python +## for循环 +class Solution: + def canJump(self, nums: List[int]) -> bool: + cover = 0 + if len(nums) == 1: return True + for i in range(len(nums)): + cover = max(i + nums[i], cover) + if cover >= len(nums) - 1: return True + return False +``` + ### Go ```Go func canJUmp(nums []int) bool { From c0f1f13669a479f6ec8d0bfe6a0b1156213363d5 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Tue, 15 Nov 2022 11:05:39 -0700 Subject: [PATCH 42/62] =?UTF-8?q?Update=200055.=E8=B7=B3=E8=B7=83=E6=B8=B8?= =?UTF-8?q?=E6=88=8F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit python for循环版,添加了更新cover的条件 --- problems/0055.跳跃游戏.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index 0ed03b07..80c35c03 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -126,8 +126,9 @@ class Solution: cover = 0 if len(nums) == 1: return True for i in range(len(nums)): - cover = max(i + nums[i], cover) - if cover >= len(nums) - 1: return True + if i <= cover: + cover = max(i + nums[i], cover) + if cover >= len(nums) - 1: return True return False ``` From 1a854c4a7e083a5b682affe7f84ccd931b74d221 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Mon, 21 Nov 2022 11:47:40 +0800 Subject: [PATCH 43/62] =?UTF-8?q?Update=201254.=E7=BB=9F=E8=AE=A1=E5=B0=81?= =?UTF-8?q?=E9=97=AD=E5=B2=9B=E5=B1=BF=E7=9A=84=E6=95=B0=E7=9B=AE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1254.统计封闭岛屿的数目.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/problems/1254.统计封闭岛屿的数目.md b/problems/1254.统计封闭岛屿的数目.md index 1270085a..dc8fda41 100644 --- a/problems/1254.统计封闭岛屿的数目.md +++ b/problems/1254.统计封闭岛屿的数目.md @@ -76,13 +76,8 @@ public: return count; } }; -``` -

- - - - -### 其他语言版本 +``` +## 其他语言版本 ### JavaScript: @@ -137,3 +132,11 @@ var closedIsland = function(grid) { return count; }; ``` + + +

+ + + + + From 27f8efa24c9d43b911fc7c05a7182508d50365cd Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Mon, 21 Nov 2022 23:12:33 +0800 Subject: [PATCH 44/62] =?UTF-8?q?=E5=9C=A8=E8=AE=BE=E8=AE=A1=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9A=84C++=E4=BB=A3=E7=A0=81=E9=83=A8=E5=88=86?= =?UTF-8?q?=EF=BC=8CaddAtIndex=E6=96=B9=E6=B3=95=E4=B8=AD=EF=BC=8C?= =?UTF-8?q?=E9=92=88=E5=AF=B9index=20<=200=20=E7=9A=84=E6=83=85=E5=86=B5?= =?UTF-8?q?=E7=BA=A0=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0707.设计链表.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 1264983b..9461e263 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -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--) { From cbe3bcf50a8633b2c07ff92b86b7bd9780d62848 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 22 Nov 2022 10:13:52 +0800 Subject: [PATCH 45/62] =?UTF-8?q?update=20027.=E7=A7=BB=E9=99=A4=E5=85=83?= =?UTF-8?q?=E7=B4=A0=20python=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0027.移除元素.md | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index e1de7243..a563a13f 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -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 Date: Tue, 22 Nov 2022 22:27:35 +0800 Subject: [PATCH 46/62] =?UTF-8?q?update=200209.=E9=95=BF=E5=BA=A6=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E7=9A=84=E5=AD=90=E6=95=B0=E7=BB=84=20python,=20js=20?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0209.长度最小的子数组.md | 66 +++++++++++-------------------- 1 file changed, 23 insertions(+), 43 deletions(-) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index c912c259..220630f2 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -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 }; ``` From af0e45b9af2171db2a2b5ef005745463a9d739e3 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Wed, 23 Nov 2022 23:34:26 +0800 Subject: [PATCH 47/62] =?UTF-8?q?update=200707.=E8=AE=BE=E8=AE=A1=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=20python=E4=BB=A3=E7=A0=81=EF=BC=8Cjava=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0707.设计链表.md | 116 +++++++++++++++++++++----------------- 1 file changed, 65 insertions(+), 51 deletions(-) diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 9461e263..f0c4bc60 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -305,7 +305,7 @@ class MyLinkedList { head = new ListNode(0); } - //获取第index个节点的数值 + //获取第index个节点的数值,注意index是从0开始的,第0个节点就是头结点 public int get(int index) { //如果index非法,返回-1 if (index < 0 || index >= size) { @@ -319,12 +319,12 @@ class MyLinkedList { return currentNode.val; } - //在链表最前面插入一个节点 + //在链表最前面插入一个节点,等价于在第0个元素前添加 public void addAtHead(int val) { addAtIndex(0, val); } - //在链表的最后插入一个节点 + //在链表的最后插入一个节点,等价于在(末尾+1)个元素前添加 public void addAtTail(int val) { addAtIndex(size, val); } @@ -481,76 +481,90 @@ class MyLinkedList { Python: ```python # 单链表 -class Node: - - def __init__(self, val): - self.val = val +class Node(object): + def __init__(self, x=0): + self.val = x self.next = None - -class MyLinkedList: +class MyLinkedList(object): def __init__(self): - self._head = Node(0) # 虚拟头部节点 - self._count = 0 # 添加的节点数 + self.head = Node() + self.size = 0 # 设置一个链表长度的属性,便于后续操作,注意每次增和删的时候都要更新 - def get(self, index: int) -> int: + def get(self, index): """ - Get the value of the index-th node in the linked list. If the index is invalid, return -1. + :type index: int + :rtype: int """ - if 0 <= index < self._count: - node = self._head - for _ in range(index + 1): - node = node.next - return node.val - else: + if index < 0 or index >= self.size: return -1 + cur = self.head.next + while(index): + cur = cur.next + index -= 1 + return cur.val - def addAtHead(self, val: int) -> None: + def addAtHead(self, val): """ - Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. + :type val: int + :rtype: None """ - self.addAtIndex(0, val) + new_node = Node(val) + new_node.next = self.head.next + self.head.next = new_node + self.size += 1 - def addAtTail(self, val: int) -> None: + def addAtTail(self, val): """ - Append a node of value val to the last element of the linked list. + :type val: int + :rtype: None """ - self.addAtIndex(self._count, val) + new_node = Node(val) + cur = self.head + while(cur.next): + cur = cur.next + cur.next = new_node + self.size += 1 - def addAtIndex(self, index: int, val: int) -> None: + def addAtIndex(self, index, val): """ - Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. + :type index: int + :type val: int + :rtype: None """ if index < 0: - index = 0 - elif index > self._count: + self.addAtHead(val) + return + elif index == self.size: + self.addAtTail(val) + return + elif index > self.size: return - # 计数累加 - self._count += 1 - - add_node = Node(val) - prev_node, current_node = None, self._head - for _ in range(index + 1): - prev_node, current_node = current_node, current_node.next - else: - prev_node.next, add_node.next = add_node, current_node - - def deleteAtIndex(self, index: int) -> None: + node = Node(val) + pre = self.head + while(index): + pre = pre.next + index -= 1 + node.next = pre.next + pre.next = node + self.size += 1 + + def deleteAtIndex(self, index): """ - Delete the index-th node in the linked list, if the index is valid. + :type index: int + :rtype: None """ - if 0 <= index < self._count: - # 计数-1 - self._count -= 1 - prev_node, current_node = None, self._head - for _ in range(index + 1): - prev_node, current_node = current_node, current_node.next - else: - prev_node.next, current_node.next = current_node.next, None - - + if index < 0 or index >= self.size: + return + pre = self.head + while(index): + pre = pre.next + index -= 1 + pre.next = pre.next.next + self.size -= 1 + # 双链表 # 相对于单链表, Node新增了prev属性 class Node: From d9950cee1bb10cb826cd1522a951cbf9ceccba81 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 24 Nov 2022 00:15:31 +0800 Subject: [PATCH 48/62] =?UTF-8?q?update=20=20=E9=9D=A2=E8=AF=95=E9=A2=9802?= =?UTF-8?q?.07.=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4=20=20python=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=20js=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 55 ++++++++++++++++++-------------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 3277e85e..30f5c467 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -155,23 +155,28 @@ public class Solution { class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: - """ - 根据快慢法则,走的快的一定会追上走得慢的。 - 在这道题里,有的链表短,他走完了就去走另一条链表,我们可以理解为走的快的指针。 - - 那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个 - 位置相遇 - """ - if headA is None or headB is None: - return None - cur_a, cur_b = headA, headB # 用两个指针代替a和b - - - while cur_a != cur_b: - cur_a = cur_a.next if cur_a else headB # 如果a走完了,那么就切换到b走 - cur_b = cur_b.next if cur_b else headA # 同理,b走完了就切换到a - - return cur_a + lenA, lenB = 0, 0 + cur = headA + while cur: # 求链表A的长度 + cur = cur.next + lenA += 1 + cur = headB + while cur: # 求链表B的长度 + cur = cur.next + lenB += 1 + curA, curB = headA, headB + if lenA > lenB: # 让curB为最长链表的头,lenB为其长度 + curA, curB = curB, curA + lenA, lenB = lenB, lenA + for _ in range(lenB - lenA): # 让curA和curB在同一起点上(末尾位置对齐) + curB = curB.next + while curA: # 遍历curA 和 curB,遇到相同则直接返回 + if curA == curB: + return curA + else: + curA = curA.next + curB = curB.next + return None ``` ### Go @@ -248,19 +253,21 @@ var getListLen = function(head) { } var getIntersectionNode = function(headA, headB) { let curA = headA,curB = headB, - lenA = getListLen(headA), - lenB = getListLen(headB); - if(lenA < lenB) { - // 下面交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时 + lenA = getListLen(headA), // 求链表A的长度 + lenB = getListLen(headB); + if(lenA < lenB) { // 让curA为最长链表的头,lenA为其长度 + + // 交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时 // 如果不加分号,下面两条代码等同于一条代码: [curA, curB] = [lenB, lenA] + [curA, curB] = [curB, curA]; [lenA, lenB] = [lenB, lenA]; } - let i = lenA - lenB; - while(i-- > 0) { + let i = lenA - lenB; // 求长度差 + while(i-- > 0) { // 让curA和curB在同一起点上(末尾位置对齐) curA = curA.next; } - while(curA && curA !== curB) { + while(curA && curA !== curB) { // 遍历curA 和 curB,遇到相同则直接返回 curA = curA.next; curB = curB.next; } From e86fea0ec398e8161149377a0fc5c5480ae680d0 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 24 Nov 2022 21:07:05 +0800 Subject: [PATCH 49/62] =?UTF-8?q?update=200242.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D=EF=BC=9A=E5=8A=A0?= =?UTF-8?q?java=E6=B3=A8=E9=87=8A=EF=BC=8C=E5=88=A0=E9=99=A4=E8=B4=A8?= =?UTF-8?q?=E9=87=8F=E8=BE=83=E5=B7=AE=E4=B8=94=E5=A4=9A=E4=BD=99=E7=9A=84?= =?UTF-8?q?go=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0242.有效的字母异位词.md | 35 +++++-------------------------- 1 file changed, 5 insertions(+), 30 deletions(-) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 1281b16b..904a0527 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -101,7 +101,7 @@ class Solution { int[] record = new int[26]; for (int i = 0; i < s.length(); i++) { - record[s.charAt(i) - 'a']++; + record[s.charAt(i) - 'a']++; // 并不需要记住字符a的ASCII,只要求出一个相对数值就可以了 } for (int i = 0; i < t.length(); i++) { @@ -109,11 +109,11 @@ class Solution { } for (int count: record) { - if (count != 0) { + if (count != 0) { // record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。 return false; } } - return true; + return true; // record数组所有元素都为零0,说明字符串s和t是字母异位词 } } ``` @@ -166,35 +166,10 @@ class Solution(object): Go: -```go -func isAnagram(s string, t string) bool { - if len(s)!=len(t){ - return false - } - exists := make(map[byte]int) - for i:=0;i=0&&ok{ - exists[s[i]]=v+1 - }else{ - exists[s[i]]=1 - } - } - for i:=0;i=1&&ok{ - exists[t[i]]=v-1 - }else{ - return false - } - } - return true -} -``` - -Go写法二(没有使用slice作为哈希表,用数组来代替): - ```go func isAnagram(s string, t string) bool { record := [26]int{} + for _, r := range s { record[r-rune('a')]++ } @@ -202,7 +177,7 @@ func isAnagram(s string, t string) bool { record[r-rune('a')]-- } - return record == [26]int{} + return record == [26]int{} // record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。 } ``` From ac58e6613bd6a9d3e265e95e285c40b05bbc6f29 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 24 Nov 2022 21:26:09 +0800 Subject: [PATCH 50/62] =?UTF-8?q?update=200349.=E4=B8=A4=E4=B8=AA=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86=20=E4=BF=AE=E6=94=B9python?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=EF=BC=8C=E5=88=A0=E9=99=A4=E5=86=97=E4=BD=99?= =?UTF-8?q?=E7=9A=84go=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0349.两个数组的交集.md | 32 ++++++++++++-------------------- 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index bd83fae9..2e98ef6f 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -147,32 +147,24 @@ Python3: ```python class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: - return list(set(nums1) & set(nums2)) # 两个数组先变成集合,求交集后还原为数组 + val_dict = {} + ans = [] + for num in nums1: + val_dict[num] = 1 + + for num in nums2: + if num in val_dict.keys() and val_dict[num] == 1: + ans.append(num) + val_dict[num] = 0 + + return ans ``` Go: ```go func intersection(nums1 []int, nums2 []int) []int { - m := make(map[int]int) - for _, v := range nums1 { - m[v] = 1 - } - var res []int - // 利用count>0,实现重复值只拿一次放入返回结果中 - for _, v := range nums2 { - if count, ok := m[v]; ok && count > 0 { - res = append(res, v) - m[v]-- - } - } - return res -} -``` -```golang -//优化版,利用set,减少count统计 -func intersection(nums1 []int, nums2 []int) []int { - set:=make(map[int]struct{},0) + set:=make(map[int]struct{},0) // 用map模拟set res:=make([]int,0) for _,v:=range nums1{ if _,ok:=set[v];!ok{ From 4796c816421924edff6bdc2521ae0880e2d80f39 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 24 Nov 2022 21:35:53 +0800 Subject: [PATCH 51/62] =?UTF-8?q?update=200001.=E4=B8=A4=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C=EF=BC=9A=E5=8A=A0=E6=B3=A8=E9=87=8A=EF=BC=8C=E7=BB=99?= =?UTF-8?q?java=E4=BB=A3=E7=A0=81=E4=B8=80=E7=82=B9=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 7bada9af..56cff527 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -134,12 +134,13 @@ public int[] twoSum(int[] nums, int target) { } Map map = new HashMap<>(); for(int i = 0; i < nums.length; i++){ - int temp = target - nums[i]; + int temp = target - nums[i]; // 遍历当前元素,并在map中寻找是否有匹配的key if(map.containsKey(temp)){ res[1] = i; res[0] = map.get(temp); + break; } - map.put(nums[i], i); + map.put(nums[i], i); // 如果没找到匹配对,就把访问过的元素和下标加入到map中 } return res; } @@ -152,16 +153,17 @@ class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: records = dict() - for index, value in enumerate(nums): - if target - value in records: + for index, value in enumerate(nums): + if target - value in records: # 遍历当前元素,并在map中寻找是否有匹配的key return [records[target- value], index] - records[value] = index + records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key return [] ``` Go: ```go +// 暴力解法 func twoSum(nums []int, target int) []int { for k1, _ := range nums { for k2 := k1 + 1; k2 < len(nums); k2++ { @@ -216,11 +218,11 @@ Javascript ```javascript var twoSum = function (nums, target) { let hash = {}; - for (let i = 0; i < nums.length; i++) { + for (let i = 0; i < nums.length; i++) { // 遍历当前元素,并在map中寻找是否有匹配的key if (hash[target - nums[i]] !== undefined) { return [i, hash[target - nums[i]]]; } - hash[nums[i]] = i; + hash[nums[i]] = i; // 如果没找到匹配对,就把访问过的元素和下标加入到map中 } return []; }; From b0f84a4b357f1413118536e55f6c37c460d32674 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 24 Nov 2022 21:42:38 +0800 Subject: [PATCH 52/62] =?UTF-8?q?update=200454.=E5=9B=9B=E6=95=B0=E7=9B=B8?= =?UTF-8?q?=E5=8A=A0II=EF=BC=9A=E5=AE=8C=E5=96=84=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0454.四数相加II.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index d9fd5c04..07c3f711 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -168,13 +168,15 @@ Go: ```go func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int { - m := make(map[int]int) + m := make(map[int]int) //key:a+b的数值,value:a+b数值出现的次数 count := 0 - for _, v1 := range nums1 { + // 遍历nums1和nums2数组,统计两个数组元素之和,和出现的次数,放到map中 + for _, v1 := range nums1 { for _, v2 := range nums2 { m[v1+v2]++ } } + // 遍历nums3和nums4数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来 for _, v3 := range nums3 { for _, v4 := range nums4 { count += m[-v3-v4] @@ -197,14 +199,14 @@ javaScript: var fourSumCount = function(nums1, nums2, nums3, nums4) { const twoSumMap = new Map(); let count = 0; - + // 统计nums1和nums2数组元素之和,和出现的次数,放到map中 for(const n1 of nums1) { for(const n2 of nums2) { const sum = n1 + n2; twoSumMap.set(sum, (twoSumMap.get(sum) || 0) + 1) } } - + // 找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来 for(const n3 of nums3) { for(const n4 of nums4) { const sum = n3 + n4; From 983bb606d39c8ea5ab384d15d8c1bb226b65bce9 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 24 Nov 2022 21:51:48 +0800 Subject: [PATCH 53/62] =?UTF-8?q?update=200383.=E8=B5=8E=E9=87=91=E4=BF=A1?= =?UTF-8?q?:=20=E5=AE=8C=E5=96=84=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0383.赎金信.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 57458308..4e6ba033 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -147,11 +147,11 @@ class Solution: arr = [0] * 26 - for x in magazine: + for x in magazine: # 记录 magazine里各个字符出现次数 arr[ord(x) - ord('a')] += 1 - for x in ransomNote: - if arr[ord(x) - ord('a')] == 0: + for x in ransomNote: # 在arr里对应的字符个数做--操作 + if arr[ord(x) - ord('a')] == 0: # 如果没有出现过直接返回 return False else: arr[ord(x) - ord('a')] -= 1 @@ -234,12 +234,12 @@ Go: ```go func canConstruct(ransomNote string, magazine string) bool { record := make([]int, 26) - for _, v := range magazine { + for _, v := range magazine { // 通过recode数据记录 magazine里各个字符出现次数 record[v-'a']++ } - for _, v := range ransomNote { + for _, v := range ransomNote { // 遍历ransomNote,在record里对应的字符个数做--操作 record[v-'a']-- - if record[v-'a'] < 0 { + if record[v-'a'] < 0 { // 如果小于零说明ransomNote里出现的字符,magazine没有 return false } } @@ -258,12 +258,12 @@ javaScript: var canConstruct = function(ransomNote, magazine) { const strArr = new Array(26).fill(0), base = "a".charCodeAt(); - for(const s of magazine) { + for(const s of magazine) { // 记录 magazine里各个字符出现次数 strArr[s.charCodeAt() - base]++; } - for(const s of ransomNote) { + for(const s of ransomNote) { // 对应的字符个数做--操作 const index = s.charCodeAt() - base; - if(!strArr[index]) return false; + if(!strArr[index]) return false; // 如果没记录过直接返回false strArr[index]--; } return true; From dddbb95ea718c7dfd327b270b4686a745d1e848d Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 24 Nov 2022 22:05:59 +0800 Subject: [PATCH 54/62] =?UTF-8?q?update=200015.=E4=B8=89=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C=EF=BC=9A=E5=AE=8C=E5=96=84=E6=B3=A8=E9=87=8A=EF=BC=8C?= =?UTF-8?q?=E4=BC=98=E5=8C=96go=E4=BB=A3=E7=A0=81=E9=A3=8E=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 56 +++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 5ee57127..6675e408 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -253,13 +253,15 @@ class Solution { public List> threeSum(int[] nums) { List> result = new ArrayList<>(); Arrays.sort(nums); - + // 找出a + b + c = 0 + // a = nums[i], b = nums[left], c = nums[right] for (int i = 0; i < nums.length; i++) { - if (nums[i] > 0) { + // 排序之后如果第一个元素已经大于零,那么无论如何组合都不可能凑成三元组,直接返回结果就可以了 + if (nums[i] > 0) { return result; } - if (i > 0 && nums[i] == nums[i - 1]) { + if (i > 0 && nums[i] == nums[i - 1]) { // 去重a continue; } @@ -273,7 +275,7 @@ class Solution { left++; } else { result.add(Arrays.asList(nums[i], nums[left], nums[right])); - + // 去重逻辑应该放在找到一个三元组之后,对b 和 c去重 while (right > left && nums[right] == nums[right - 1]) right--; while (right > left && nums[left] == nums[left + 1]) left++; @@ -294,12 +296,15 @@ class Solution: ans = [] n = len(nums) nums.sort() + # 找出a + b + c = 0 + # a = nums[i], b = nums[left], c = nums[right] for i in range(n): left = i + 1 right = n - 1 - if nums[i] > 0: + # 排序之后如果第一个元素已经大于零,那么无论如何组合都不可能凑成三元组,直接返回结果就可以了 + if nums[i] > 0: break - if i >= 1 and nums[i] == nums[i - 1]: + if i >= 1 and nums[i] == nums[i - 1]: # 去重a continue while left < right: total = nums[i] + nums[left] + nums[right] @@ -309,13 +314,14 @@ class Solution: left += 1 else: ans.append([nums[i], nums[left], nums[right]]) + # 去重逻辑应该放在找到一个三元组之后,对b 和 c去重 while left != right and nums[left] == nums[left + 1]: left += 1 while left != right and nums[right] == nums[right - 1]: right -= 1 left += 1 right -= 1 return ans ``` -Python (v2): +Python (v3): ```python class Solution: @@ -344,32 +350,36 @@ class Solution: Go: ```Go -func threeSum(nums []int)[][]int{ +func threeSum(nums []int) [][]int { sort.Ints(nums) - res:=[][]int{} - - for i:=0;i0{ + res := [][]int{} + // 找出a + b + c = 0 + // a = nums[i], b = nums[left], c = nums[right] + for i := 0; i < len(nums)-2; i++ { + // 排序之后如果第一个元素已经大于零,那么无论如何组合都不可能凑成三元组,直接返回结果就可以了 + n1 := nums[i] + if n1 > 0 { break } - if i>0&&n1==nums[i-1]{ + // 去重a + if i > 0 && n1 == nums[i-1] { continue } - l,r:=i+1,len(nums)-1 - for l Date: Thu, 24 Nov 2022 22:12:59 +0800 Subject: [PATCH 55/62] =?UTF-8?q?update=200018.=E5=9B=9B=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C=20=E5=AE=8C=E5=96=84=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0018.四数之和.md | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index ca33eb57..3fc80bba 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -136,25 +136,26 @@ class Solution { Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { - + // nums[i] > target 直接返回, 剪枝操作 if (nums[i] > 0 && nums[i] > target) { return result; } - - if (i > 0 && nums[i - 1] == nums[i]) { + + if (i > 0 && nums[i - 1] == nums[i]) { // 对nums[i]去重 continue; } for (int j = i + 1; j < nums.length; j++) { - if (j > i + 1 && nums[j - 1] == nums[j]) { + if (j > i + 1 && nums[j - 1] == nums[j]) { // 对nums[j]去重 continue; } int left = j + 1; int right = nums.length - 1; while (right > left) { + // nums[k] + nums[i] + nums[left] + nums[right] > target int会溢出 long sum = (long) nums[i] + nums[j] + nums[left] + nums[right]; if (sum > target) { right--; @@ -162,7 +163,7 @@ class Solution { left++; } else { result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); - + // 对nums[left]和nums[right]去重 while (right > left && nums[right] == nums[right - 1]) right--; while (right > left && nums[left] == nums[left + 1]) left++; @@ -186,10 +187,10 @@ class Solution: nums.sort() n = len(nums) res = [] - for i in range(n): - if i > 0 and nums[i] == nums[i - 1]: continue + for i in range(n): + if i > 0 and nums[i] == nums[i - 1]: continue # 对nums[i]去重 for k in range(i+1, n): - if k > i + 1 and nums[k] == nums[k-1]: continue + if k > i + 1 and nums[k] == nums[k-1]: continue # 对nums[k]去重 p = k + 1 q = n - 1 @@ -198,6 +199,7 @@ class Solution: elif nums[i] + nums[k] + nums[p] + nums[q] < target: p += 1 else: res.append([nums[i], nums[k], nums[p], nums[q]]) + # 对nums[p]和nums[q]去重 while p < q and nums[p] == nums[p + 1]: p += 1 while p < q and nums[q] == nums[q - 1]: q -= 1 p += 1 @@ -258,12 +260,12 @@ func fourSum(nums []int, target int) [][]int { // if n1 > target { // 不能这样写,因为可能是负数 // break // } - if i > 0 && n1 == nums[i-1] { + if i > 0 && n1 == nums[i-1] { // 对nums[i]去重 continue } for j := i + 1; j < len(nums)-2; j++ { n2 := nums[j] - if j > i+1 && n2 == nums[j-1] { + if j > i+1 && n2 == nums[j-1] { // 对nums[j]去重 continue } l := j + 1 @@ -320,6 +322,8 @@ var fourSum = function(nums, target) { if(sum < target) { l++; continue} if(sum > target) { r--; continue} res.push([nums[i], nums[j], nums[l], nums[r]]); + + // 对nums[left]和nums[right]去重 while(l < r && nums[l] === nums[++l]); while(l < r && nums[r] === nums[--r]); } From 45dad67adf152317ae97b9c50ea82fce4fe53c31 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Fri, 25 Nov 2022 23:54:31 +0800 Subject: [PATCH 56/62] =?UTF-8?q?update=200344.=E5=8F=8D=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=20=E4=BC=98=E5=8C=96go=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0344.反转字符串.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index 2807d04a..c4803311 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -190,11 +190,11 @@ class Solution: Go: ```Go -func reverseString(s []byte) { - left:=0 - right:=len(s)-1 - for left Date: Sat, 26 Nov 2022 00:07:59 +0800 Subject: [PATCH 57/62] =?UTF-8?q?update=200541.=E5=8F=8D=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2II=EF=BC=9A=E8=A1=A5=E5=85=85=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0541.反转字符串II.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 59891365..516f78da 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -294,6 +294,8 @@ func reverseStr(s string, k int) string { ss := []byte(s) length := len(s) for i := 0; i < length; i += 2 * k { + // 1. 每隔 2k 个字符的前 k 个字符进行反转 + // 2. 剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符 if i + k <= length { reverse(ss[i:i+k]) } else { @@ -326,7 +328,7 @@ javaScript: var reverseStr = function(s, k) { const len = s.length; let resArr = s.split(""); - for(let i = 0; i < len; i += 2 * k) { + for(let i = 0; i < len; i += 2 * k) { // 每隔 2k 个字符的前 k 个字符进行反转 let l = i - 1, r = i + k > len ? len : i + k; while(++l < --r) [resArr[l], resArr[r]] = [resArr[r], resArr[l]]; } From e7c9a43b41af1eddb9594527bad8b7d8546eae81 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Sat, 26 Nov 2022 17:28:34 +0800 Subject: [PATCH 58/62] =?UTF-8?q?update=20=E5=89=91=E6=8C=87Offer05.?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC:=20=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E7=97=85=E5=8F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer05.替换空格.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 53f0315f..ab6eedf7 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -36,7 +36,7 @@ i指向新长度的末尾,j指向旧长度的末尾。 这么做有两个好处: 1. 不用申请新数组。 -2. 从后向前填充元素,避免了从前先后填充元素要来的 每次添加元素都要将添加元素之后的所有元素向后移动。 +2. 从后向前填充元素,避免了从前向后填充元素时,每次添加元素都要将添加元素之后的所有元素向后移动的问题。 时间复杂度,空间复杂度均超过100%的用户。 From 29624142179dd8f403753ede58ebcc6705684eb7 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Sat, 26 Nov 2022 17:42:51 +0800 Subject: [PATCH 59/62] =?UTF-8?q?update=200151.=E7=BF=BB=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D:=20?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=94=99=E5=AD=97=EF=BC=8C=E4=BC=98=E5=8C=96?= =?UTF-8?q?python=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0151.翻转字符串里的单词.md | 74 +++++++++++++++-------------- 1 file changed, 38 insertions(+), 36 deletions(-) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 450d7258..b82204fa 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -119,7 +119,7 @@ void removeExtraSpaces(string& s) { 1. leetcode上的测试集里,字符串的长度不够长,如果足够长,性能差距会非常明显。 2. leetcode的测程序耗时不是很准确的。 -版本一的代码是比较如何一般思考过程,就是 先移除字符串钱的空格,在移除中间的,在移除后面部分。 +版本一的代码是一般的思考过程,就是 先移除字符串前的空格,再移除中间的,再移除后面部分。 不过其实还可以优化,这部分和[27.移除元素](https://programmercarl.com/0027.移除元素.html)的逻辑是一样一样的,本题是移除空格,而 27.移除元素 就是移除元素。 @@ -145,7 +145,7 @@ void removeExtraSpaces(string& s) {//去除所有空格并在相邻单词之间 此时我们已经实现了removeExtraSpaces函数来移除冗余空格。 -还做实现反转字符串的功能,支持反转字符串子区间,这个实现我们分别在[344.反转字符串](https://programmercarl.com/0344.反转字符串.html)和[541.反转字符串II](https://programmercarl.com/0541.反转字符串II.html)里已经讲过了。 +还要实现反转字符串的功能,支持反转字符串子区间,这个实现我们分别在[344.反转字符串](https://programmercarl.com/0344.反转字符串.html)和[541.反转字符串II](https://programmercarl.com/0541.反转字符串II.html)里已经讲过了。 代码如下: @@ -434,49 +434,51 @@ python: ```Python class Solution: #1.去除多余的空格 - def trim_spaces(self,s): - n=len(s) - left=0 - right=n-1 + def trim_spaces(self, s): + n = len(s) + left = 0 + right = n-1 - while left<=right and s[left]==' ': #去除开头的空格 - left+=1 - while left<=right and s[right]==' ': #去除结尾的空格 - right=right-1 - tmp=[] - while left<=right: #去除单词中间多余的空格 - if s[left]!=' ': + while left <= right and s[left] == ' ': #去除开头的空格 + left += 1 + while left <= right and s[right] == ' ': #去除结尾的空格 + right = right-1 + tmp = [] + while left <= right: #去除单词中间多余的空格 + if s[left] != ' ': tmp.append(s[left]) - elif tmp[-1]!=' ': #当前位置是空格,但是相邻的上一个位置不是空格,则该空格是合理的 + elif tmp[-1] != ' ': #当前位置是空格,但是相邻的上一个位置不是空格,则该空格是合理的 tmp.append(s[left]) - left+=1 + left += 1 return tmp -#2.翻转字符数组 - def reverse_string(self,nums,left,right): - while left Date: Sat, 26 Nov 2022 17:50:07 +0800 Subject: [PATCH 60/62] =?UTF-8?q?update=20=E5=89=91=E6=8C=87Offer58-II.?= =?UTF-8?q?=E5=B7=A6=E6=97=8B=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2=EF=BC=9A?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=94=99=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer58-II.左旋转字符串.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index c34b2a71..1b619ffb 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -31,7 +31,7 @@ 不能使用额外空间的话,模拟在本串操作要实现左旋转字符串的功能还是有点困难的。 -那么我们可以想一下上一题目[字符串:花式反转还不够!](https://programmercarl.com/0151.翻转字符串里的单词.html)中讲过,使用整体反转+局部反转就可以实现,反转单词顺序的目的。 +那么我们可以想一下上一题目[字符串:花式反转还不够!](https://programmercarl.com/0151.翻转字符串里的单词.html)中讲过,使用整体反转+局部反转就可以实现反转单词顺序的目的。 这道题目也非常类似,依然可以通过局部反转+整体反转 达到左旋转的目的。 @@ -41,7 +41,7 @@ 2. 反转区间为n到末尾的子串 3. 反转整个字符串 -最后就可以得到左旋n的目的,而不用定义新的字符串,完全在本串上操作。 +最后就可以达到左旋n的目的,而不用定义新的字符串,完全在本串上操作。 例如 :示例1中 输入:字符串abcdefg,n=2 @@ -75,7 +75,7 @@ public: 在这篇文章[344.反转字符串](https://programmercarl.com/0344.反转字符串.html),第一次讲到反转一个字符串应该怎么做,使用了双指针法。 -然后发现[541. 反转字符串II](https://programmercarl.com/0541.反转字符串II.html),这里开始给反转加上了一些条件,当需要固定规律一段一段去处理字符串的时候,要想想在在for循环的表达式上做做文章。 +然后发现[541. 反转字符串II](https://programmercarl.com/0541.反转字符串II.html),这里开始给反转加上了一些条件,当需要固定规律一段一段去处理字符串的时候,要想想在for循环的表达式上做做文章。 后来在[151.翻转字符串里的单词](https://programmercarl.com/0151.翻转字符串里的单词.html)中,要对一句话里的单词顺序进行反转,发现先整体反转再局部反转 是一个很妙的思路。 From f95a4b6ab42d7156df54091b7d96fdf913dfd44c Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Sat, 26 Nov 2022 20:48:23 +0800 Subject: [PATCH 61/62] =?UTF-8?q?update=200028.=E5=AE=9E=E7=8E=B0strStr?= =?UTF-8?q?=EF=BC=9A=E6=94=B9=E9=94=99=E5=AD=97=EF=BC=8C=E4=BC=98=E5=8C=96?= =?UTF-8?q?python=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0028.实现strStr.md | 124 ++++++++++++++++++------------------ 1 file changed, 62 insertions(+), 62 deletions(-) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 19d16e9f..fc222441 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -94,7 +94,7 @@ next数组就是一个前缀表(prefix table)。 **前缀表是用来回退的,它记录了模式串与主串(文本串)不匹配的时候,模式串应该从哪里开始重新匹配。** -为了清楚的了解前缀表的来历,我们来举一个例子: +为了清楚地了解前缀表的来历,我们来举一个例子: 要在文本串:aabaabaafa 中查找是否出现过一个模式串:aabaaf。 @@ -110,9 +110,9 @@ next数组就是一个前缀表(prefix table)。 ![KMP详解1](https://code-thinking.cdn.bcebos.com/gifs/KMP%E7%B2%BE%E8%AE%B21.gif) -动画里,我特意把 子串`aa` 标记上了,这是有原因的,大家先注意一下,后面还会说道。 +动画里,我特意把 子串`aa` 标记上了,这是有原因的,大家先注意一下,后面还会说到。 -可以看出,文本串中第六个字符b 和 模式串的第六个字符f,不匹配了。如果暴力匹配,会发现不匹配,此时就要从头匹配了。 +可以看出,文本串中第六个字符b 和 模式串的第六个字符f,不匹配了。如果暴力匹配,发现不匹配,此时就要从头匹配了。 但如果使用前缀表,就不会从头匹配,而是从上次已经匹配的内容开始匹配,找到了模式串中第三个字符b继续开始匹配。 @@ -157,7 +157,7 @@ next数组就是一个前缀表(prefix table)。 以下这句话,对于理解为什么使用前缀表可以告诉我们匹配失败之后跳到哪里重新匹配 非常重要! -**下标5之前这部分的字符串(也就是字符串aabaa)的最长相等的前缀 和 后缀字符串是 子字符串aa ,因为找到了最长相等的前缀和后缀,匹配失败的位置是后缀子串的后面,那么我们找到与其相同的前缀的后面从新匹配就可以了。** +**下标5之前这部分的字符串(也就是字符串aabaa)的最长相等的前缀 和 后缀字符串是 子字符串aa ,因为找到了最长相等的前缀和后缀,匹配失败的位置是后缀子串的后面,那么我们找到与其相同的前缀的后面重新匹配就可以了。** 所以前缀表具有告诉我们当前位置匹配失败,跳到之前已经匹配过的地方的能力。 @@ -199,7 +199,7 @@ next数组就是一个前缀表(prefix table)。 所以要看前一位的 前缀表的数值。 -前一个字符的前缀表的数值是2, 所有把下标移动到下标2的位置继续比配。 可以再反复看一下上面的动画。 +前一个字符的前缀表的数值是2, 所以把下标移动到下标2的位置继续比配。 可以再反复看一下上面的动画。 最后就在文本串中找到了和模式串匹配的子串了。 @@ -211,7 +211,7 @@ next数组就可以是前缀表,但是很多实现都是把前缀表统一减 为什么这么做呢,其实也是很多文章视频没有解释清楚的地方。 -其实**这并不涉及到KMP的原理,而是具体实现,next数组即可以就是前缀表,也可以是前缀表统一减一(右移一位,初始位置为-1)。** +其实**这并不涉及到KMP的原理,而是具体实现,next数组既可以就是前缀表,也可以是前缀表统一减一(右移一位,初始位置为-1)。** 后面我会提供两种不同的实现代码,大家就明白了。 @@ -231,7 +231,7 @@ next数组就可以是前缀表,但是很多实现都是把前缀表统一减 其中n为文本串长度,m为模式串长度,因为在匹配的过程中,根据前缀表不断调整匹配的位置,可以看出匹配的过程是O(n),之前还要单独生成next数组,时间复杂度是O(m)。所以整个KMP算法的时间复杂度是O(n+m)的。 -暴力的解法显而易见是O(n × m),所以**KMP在字符串匹配中极大的提高的搜索的效率。** +暴力的解法显而易见是O(n × m),所以**KMP在字符串匹配中极大地提高了搜索的效率。** 为了和力扣题目28.实现strStr保持一致,方便大家理解,以下文章统称haystack为文本串, needle为模式串。 @@ -251,7 +251,7 @@ void getNext(int* next, const string& s) 2. 处理前后缀不相同的情况 3. 处理前后缀相同的情况 -接下来我们详解详解一下。 +接下来我们详解一下。 1. 初始化: @@ -613,12 +613,12 @@ class Solution { public void getNext(int[] next, String s){ int j = -1; next[0] = j; - for (int i = 1; i=0 && s.charAt(i) != s.charAt(j+1)){ + for (int i = 1; i < s.length(); i++){ + while(j >= 0 && s.charAt(i) != s.charAt(j+1)){ j=next[j]; } - if(s.charAt(i)==s.charAt(j+1)){ + if(s.charAt(i) == s.charAt(j+1)){ j++; } next[i] = j; @@ -632,14 +632,14 @@ class Solution { int[] next = new int[needle.length()]; getNext(next, needle); int j = -1; - for(int i = 0; i=0 && haystack.charAt(i) != needle.charAt(j+1)){ j = next[j]; } - if(haystack.charAt(i)==needle.charAt(j+1)){ + if(haystack.charAt(i) == needle.charAt(j+1)){ j++; } - if(j==needle.length()-1){ + if(j == needle.length()-1){ return (i-needle.length()+1); } } @@ -694,9 +694,9 @@ class Solution(object): :type needle: str :rtype: int """ - m,n=len(haystack),len(needle) + m, n = len(haystack), len(needle) for i in range(m): - if haystack[i:i+n]==needle: + if haystack[i:i+n] == needle: return i return -1 ``` @@ -704,31 +704,31 @@ class Solution(object): // 方法一 class Solution: def strStr(self, haystack: str, needle: str) -> int: - a=len(needle) - b=len(haystack) - if a==0: + a = len(needle) + b = len(haystack) + if a == 0: return 0 - next=self.getnext(a,needle) + next = self.getnext(a,needle) p=-1 for j in range(b): - while p>=0 and needle[p+1]!=haystack[j]: - p=next[p] - if needle[p+1]==haystack[j]: - p+=1 - if p==a-1: + while p >= 0 and needle[p+1] != haystack[j]: + p = next[p] + if needle[p+1] == haystack[j]: + p += 1 + if p == a-1: return j-a+1 return -1 def getnext(self,a,needle): - next=['' for i in range(a)] - k=-1 - next[0]=k - for i in range(1,len(needle)): - while (k>-1 and needle[k+1]!=needle[i]): - k=next[k] - if needle[k+1]==needle[i]: - k+=1 - next[i]=k + next = ['' for i in range(a)] + k = -1 + next[0] = k + for i in range(1, len(needle)): + while (k > -1 and needle[k+1] != needle[i]): + k = next[k] + if needle[k+1] == needle[i]: + k += 1 + next[i] = k return next ``` @@ -736,34 +736,34 @@ class Solution: // 方法二 class Solution: def strStr(self, haystack: str, needle: str) -> int: - a=len(needle) - b=len(haystack) - if a==0: + a = len(needle) + b = len(haystack) + if a == 0: return 0 - i=j=0 - next=self.getnext(a,needle) - while(i= 0 && s[i] != s[j+1] { - j = next[j] // 回退前一位 + j = next[j] // 回退前一位 } if s[i] == s[j+1] { j++ } - next[i] = j // next[i]是i(包括i)之前的最长相等前后缀长度 + next[i] = j // next[i]是i(包括i)之前的最长相等前后缀长度 } } func strStr(haystack string, needle string) int { @@ -796,15 +796,15 @@ func strStr(haystack string, needle string) int { } next := make([]int, len(needle)) getNext(next, needle) - j := -1 // 模式串的起始位置 next为-1 因此也为-1 + j := -1 // 模式串的起始位置 next为-1 因此也为-1 for i := 0; i < len(haystack); i++ { for j >= 0 && haystack[i] != needle[j+1] { - j = next[j] // 寻找下一个匹配点 + j = next[j] // 寻找下一个匹配点 } if haystack[i] == needle[j+1] { j++ } - if j == len(needle)-1 { // j指向了模式串的末尾 + if j == len(needle)-1 { // j指向了模式串的末尾 return i - len(needle) + 1 } } @@ -842,7 +842,7 @@ func strStr(haystack string, needle string) int { getNext(next, needle) for i := 0; i < len(haystack); i++ { for j > 0 && haystack[i] != needle[j] { - j = next[j-1] // 回退到j的前一位 + j = next[j-1] // 回退到j的前一位 } if haystack[i] == needle[j] { j++ From 7ebd52477dcd5cfeb45f700ff1b2bb2023e6b6c1 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Sat, 26 Nov 2022 21:13:49 +0800 Subject: [PATCH 62/62] =?UTF-8?q?update=200459.=E9=87=8D=E5=A4=8D=E7=9A=84?= =?UTF-8?q?=E5=AD=90=E5=AD=97=E7=AC=A6=E4=B8=B2:=E6=94=B9=E9=94=99?= =?UTF-8?q?=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0459.重复的子字符串.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index b7d86880..5d870219 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -46,17 +46,17 @@ ## 移动匹配 -当一个字符串s:abcabc,内部又重复的子串组成,那么这个字符串的结构一定是这样的: +当一个字符串s:abcabc,内部由重复的子串组成,那么这个字符串的结构一定是这样的: ![图一](https://code-thinking-1253855093.file.myqcloud.com/pics/20220728104518.png) -也就是又前后又相同的子串组成。 +也就是由前后相同的子串组成。 那么既然前面有相同的子串,后面有相同的子串,用 s + s,这样组成的字符串中,后面的子串做前串,前后的子串做后串,就一定还能组成一个s,如图: ![图二](https://code-thinking-1253855093.file.myqcloud.com/pics/20220728104931.png) -所以判断字符串s是否有重复子串组成,只要两个s拼接在一起,里面还出现一个s的话,就说明是又重复子串组成。 +所以判断字符串s是否由重复子串组成,只要两个s拼接在一起,里面还出现一个s的话,就说明是由重复子串组成。 当然,我们在判断 s + s 拼接的字符串里是否出现一个s的的时候,**要刨除 s + s 的首字符和尾字符**,这样避免在s+s中搜索出原来的s,我们要搜索的是中间拼接出来的s。 @@ -81,7 +81,7 @@ public: ## KMP ### 为什么会使用KMP -以下使用KMP方式讲解,强烈建议大家先把一下两个视频看了,理解KMP算法,在来看下面讲解,否则会很懵。 +以下使用KMP方式讲解,强烈建议大家先把以下两个视频看了,理解KMP算法,再来看下面讲解,否则会很懵。 * [视频讲解版:帮你把KMP算法学个通透!(理论篇)](https://www.bilibili.com/video/BV1PD4y1o7nd/) * [视频讲解版:帮你把KMP算法学个通透!(求next数组代码篇)](https://www.bilibili.com/video/BV1M5411j7Xx) @@ -93,12 +93,12 @@ KMP算法中next数组为什么遇到字符不匹配的时候可以找到上一 那么 最长相同前后缀和重复子串的关系又有什么关系呢。 -可能很多录友又忘了 前缀和后缀的定义,在回顾一下: +可能很多录友又忘了 前缀和后缀的定义,再回顾一下: * 前缀是指不包含最后一个字符的所有以第一个字符开头的连续子串; * 后缀是指不包含第一个字符的所有以最后一个字符结尾的连续子串 -在由重复子串组成的字符串中,最长相等前后缀不包含的子串就是最小重复子串,这里那字符串s:abababab 来举例,ab就是最小重复单位,如图所示: +在由重复子串组成的字符串中,最长相等前后缀不包含的子串就是最小重复子串,这里拿字符串s:abababab 来举例,ab就是最小重复单位,如图所示: ![图三](https://code-thinking-1253855093.file.myqcloud.com/pics/20220728205249.png) @@ -123,11 +123,11 @@ KMP算法中next数组为什么遇到字符不匹配的时候可以找到上一 ### 简单推理 -这里在给出一个数推导,就容易理解很多。 +这里再给出一个数学推导,就容易理解很多。 假设字符串s使用多个重复子串构成(这个子串是最小重复单位),重复出现的子字符串长度是x,所以s是由n * x组成。 -因为字符串s的最长相同前后缀的的长度一定是不包含s本身,所以 最长相同前后缀长度必然是m * x,而且 n - m = 1,(这里如果不懂,看上面的推理) +因为字符串s的最长相同前后缀的长度一定是不包含s本身,所以 最长相同前后缀长度必然是m * x,而且 n - m = 1,(这里如果不懂,看上面的推理) 所以如果 nx % (n - m)x = 0,就可以判定有重复出现的子字符串。