From f8f8539393813c4f4ec73427d5eb157acc641fe1 Mon Sep 17 00:00:00 2001 From: Yifan Liu <39271063+yifanliuu@users.noreply.github.com> Date: Thu, 29 Jun 2023 13:49:22 +0800 Subject: [PATCH 01/26] =?UTF-8?q?=E6=96=B0=E5=A2=9Epython=E8=A7=A3?= =?UTF-8?q?=E6=B3=95=E9=80=92=E5=BD=92=E7=89=88=200024.=E4=B8=A4=E4=B8=A4?= =?UTF-8?q?=E4=BA=A4=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82?= =?UTF-8?q?=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0024.两两交换链表中的节点.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index ab204d89..d7c03b64 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -177,6 +177,30 @@ class Solution { ``` Python: +```python +# 递归版本 +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class Solution: + def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: + if head is None or head.next is None: + return head + + # 待翻转的两个node分别是pre和cur + pre = head + cur = head.next + next = head.next.next + + cur.next = pre # 交换 + pre.next = self.swapPairs(next) # 将以next为head的后续链表两两交换 + + return cur +``` + ```python # Definition for singly-linked list. # class ListNode: From 5085e78e601fa6450e80b0d5d9b060df26857dcb Mon Sep 17 00:00:00 2001 From: Leon He Date: Thu, 29 Jun 2023 11:25:27 -0700 Subject: [PATCH 02/26] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF=E6=95=B0?= =?UTF-8?q?=E9=87=8F.=E5=B9=BF=E6=90=9C=E7=89=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add python solution --- problems/0200.岛屿数量.广搜版.md | 41 +++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index 39af9f50..2bb0973a 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -200,3 +200,44 @@ class Solution { +``` +### Python +BFS solution +```python +class Solution: + def __init__(self): + self.dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]] + + def numIslands(self, grid: List[List[str]]) -> int: + m = len(grid) + n = len(grid[0]) + visited = [[False]*n for _ in range(m)] + res = 0 + for i in range(m): + for j in range(n): + if visited[i][j] == False and grid[i][j] == '1': + res += 1 + self.bfs(grid, i, j, visited) # Call bfs within this condition + return res + + def bfs(self, grid, i, j, visited): + q = deque() + q.append((i,j)) + visited[i][j] = True + while q: + x, y = q.popleft() + for k in range(4): + next_i = x + self.dirs[k][0] + next_j = y + self.dirs[k][1] + + if next_i < 0 or next_i >= len(grid): + continue + if next_j < 0 or next_j >= len(grid[0]): + continue + if visited[next_i][next_j]: + continue + if grid[next_i][next_j] == '0': + continue + q.append((next_i, next_j)) + visited[next_i][next_j] = True +``` From 6cd9b165290298868b6b86ca88693c5b77408841 Mon Sep 17 00:00:00 2001 From: Terry Liu <102352821+Lozakaka@users.noreply.github.com> Date: Thu, 29 Jun 2023 16:56:19 -0400 Subject: [PATCH 03/26] =?UTF-8?q?=E6=96=B0=E5=A2=9Ejava=20DFS=E8=A7=A3?= =?UTF-8?q?=E6=B3=95=E7=95=B6=E4=BD=9C=E5=BB=B6=E4=BC=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0463.岛屿的周长.md | 47 ++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0463.岛屿的周长.md b/problems/0463.岛屿的周长.md index 2f399f40..18f1d01e 100644 --- a/problems/0463.岛屿的周长.md +++ b/problems/0463.岛屿的周长.md @@ -142,6 +142,53 @@ class Solution { return landSum * 4 - cover * 2; } } +// 延伸 - 傳統DFS解法(使用visited數組)(遇到邊界 或是 海水 就edge ++) +class Solution { + int dir[][] ={ + {0, 1}, + {0, -1}, + {1, 0}, + {-1, 0} + }; + + boolean visited[][]; + int res = 0; + + public int islandPerimeter(int[][] grid) { + int row = grid.length; + int col = grid[0].length; + visited = new boolean[row][col]; + + int result = 0; + + for(int i = 0; i < row; i++){ + for(int j = 0; j < col; j++){ + if(visited[i][j] == false && grid[i][j] == 1) + result += dfs(grid, i, j); + } + } + return result; + } + + private int dfs(int[][] grid, int x, int y){ + //如果遇到 邊界(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length)或是 遇到海水(grid[x][y] == 0)就return 1(edge + 1) + if(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == 0) + return 1; + //如果該地已經拜訪過,就return 0 避免重複計算 + if(visited[x][y]) + return 0; + int temp = 0; + visited[x][y] = true; + for(int i = 0; i < 4; i++){ + int nextX = x + dir[i][0]; + int nextY = y + dir[i][1]; + //用temp 把edge存起來 + temp +=dfs(grid, nextX, nextY); + } + return temp; + } +} + ``` Python: From c1b2141ea20e58b031c874f55c341fbfc8b69470 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 30 Jun 2023 10:22:49 +0800 Subject: [PATCH 04/26] =?UTF-8?q?Update=200123.=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=BAIII.md=20?= =?UTF-8?q?about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0123.买卖股票的最佳时机III.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 6ac9a576..f5b95946 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -413,7 +413,34 @@ function maxProfit(prices: number[]): number { }; ``` +Rust: +> 版本一 + +```rust +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + /* + * 定义 5 种状态: + * 0: 没有操作, 1: 第一次买入, 2: 第一次卖出, 3: 第二次买入, 4: 第二次卖出 + */ + let mut dp = vec![vec![0; 5]; prices.len()]; + dp[0][1] = -prices[0]; + dp[0][3] = -prices[0]; + + for (i, &p) in prices.iter().enumerate().skip(1) { + // 不操作 + // dp[i][0] = dp[i - 1][0]; + dp[i][1] = dp[i - 1][1].max(-p); + dp[i][2] = dp[i - 1][2].max(dp[i - 1][1] + p); + dp[i][3] = dp[i - 1][3].max(dp[i - 1][2] - p); + dp[i][4] = dp[i - 1][4].max(dp[i - 1][3] + p); + } + + dp[prices.len() - 1][4] + } +} +```

From 85daaae4656f0411eab2e1ec6ff1bbfa608120c1 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 30 Jun 2023 10:31:32 +0800 Subject: [PATCH 05/26] =?UTF-8?q?Update=200123.=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=BAIII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0123.买卖股票的最佳时机III.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index f5b95946..7286e957 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -442,6 +442,24 @@ impl Solution { } ``` +> 版本二(绕) + +```rust +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut dp = vec![0, -prices[0], 0, -prices[0], 0]; + + for p in prices { + dp[1] = dp[1].max(-p); + dp[2] = dp[2].max(dp[1] + p); + dp[3] = dp[3].max(dp[2] - p); + dp[4] = dp[4].max(dp[3] + p); + } + dp[4] + } +} +``` +

From 2444c084b15fce271ac3639bca32bc579c594ad1 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 30 Jun 2023 11:33:23 +0800 Subject: [PATCH 06/26] =?UTF-8?q?Update=200188.=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=BAIV.md=20a?= =?UTF-8?q?bout=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0188.买卖股票的最佳时机IV.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 5bed5ecc..8cfb4c1b 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -439,6 +439,28 @@ function maxProfit(k: number, prices: number[]): number { }; ``` +Rust: + +```rust +impl Solution { + pub fn max_profit(k: i32, prices: Vec) -> i32 { + let mut dp = vec![vec![0; 2 * k as usize + 1]; prices.len()]; + + for v in dp[0].iter_mut().skip(1).step_by(2) { + *v = -prices[0]; + } + + for (i, &p) in prices.iter().enumerate().skip(1) { + for j in (0..2 * k as usize - 1).step_by(2) { + dp[i][j + 1] = dp[i - 1][j + 1].max(dp[i - 1][j] - p); + dp[i][j + 2] = dp[i - 1][j + 2].max(dp[i - 1][j + 1] + p); + } + } + + dp[prices.len() - 1][2 * k as usize] + } +} +```

From e452f183adde4732da370e14dc0379ebffd0bdbe Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 30 Jun 2023 13:14:26 +0800 Subject: [PATCH 07/26] =?UTF-8?q?Update=200123.=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=BAIII.md=20?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=85=83=E7=A5=96=E4=BC=98=E5=8C=96=E5=91=BD?= =?UTF-8?q?=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0123.买卖股票的最佳时机III.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 7286e957..a646b7d5 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -447,15 +447,15 @@ impl Solution { ```rust impl Solution { pub fn max_profit(prices: Vec) -> i32 { - let mut dp = vec![0, -prices[0], 0, -prices[0], 0]; + let (mut one_buy, mut one_sale, mut two_buy, mut two_sale) = (-prices[0], 0, -prices[0], 0); for p in prices { - dp[1] = dp[1].max(-p); - dp[2] = dp[2].max(dp[1] + p); - dp[3] = dp[3].max(dp[2] - p); - dp[4] = dp[4].max(dp[3] + p); + one_buy = one_buy.max(-p); + one_sale = one_sale.max(p + one_buy); + two_buy = two_buy.max(one_sale - p); + two_sale = two_sale.max(two_buy + p); } - dp[4] + two_sale } } ``` From c4a7033e50a8713808654ac4b179ca4883b4998f Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 30 Jun 2023 13:45:44 +0800 Subject: [PATCH 08/26] =?UTF-8?q?Update=200188.=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=BAIV.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0188.买卖股票的最佳时机IV.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 8cfb4c1b..fb1a6898 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -462,6 +462,33 @@ impl Solution { } ``` +空间优化: + +```rust +impl Solution { + pub fn max_profit(k: i32, prices: Vec) -> i32 { + let mut dp = vec![0; 2 * k as usize + 1]; + for v in dp.iter_mut().skip(1).step_by(2) { + *v = -prices[0]; + } + + for p in prices { + for i in 1..=2 * k as usize { + if i % 2 == 1 { + // 买入 + dp[i] = dp[i].max(dp[i - 1] - p); + continue; + } + // 卖出 + dp[i] = dp[i].max(dp[i - 1] + p); + } + } + + dp[2 * k as usize] + } +} +``` +

From e5d3d1188555ea83aa00c156afcc249d4fd1fe42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Sun, 16 Jul 2023 20:39:00 +0800 Subject: [PATCH 09/26] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF=E6=95=B0?= =?UTF-8?q?=E9=87=8F.=E5=B9=BF=E6=90=9C=E7=89=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.广搜版.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index 2bb0973a..c20fe4f1 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -196,11 +196,8 @@ class Solution { } } ``` -

- - - -``` + +## 其他语言版本 ### Python BFS solution ```python @@ -241,3 +238,9 @@ class Solution: q.append((next_i, next_j)) visited[next_i][next_j] = True ``` + +

+ + + +``` From 3a76b3a85e097446ab5f9e7dbb6028bac81c75de Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Mon, 17 Jul 2023 11:52:50 +0800 Subject: [PATCH 10/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200704.=E4=BA=8C?= =?UTF-8?q?=E5=88=86=E6=9F=A5=E6=89=BE=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0704.二分查找.md | 36 +++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index c59ae868..d202dfa1 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -35,7 +35,7 @@ ## 算法公开课 -***[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[手把手带你撕出正确的二分法](https://www.bilibili.com/video/BV1fA4y1o715),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 +**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[手把手带你撕出正确的二分法](https://www.bilibili.com/video/BV1fA4y1o715),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 ## 思路 @@ -160,7 +160,7 @@ public: ## 其他语言版本 -**Java:** +### **Java:** (版本一)左闭右闭区间 @@ -206,7 +206,7 @@ class Solution { } ``` -**Python:** +### **Python:** (版本一)左闭右闭区间 @@ -246,7 +246,7 @@ class Solution: return -1 # 未找到目标值 ``` -**Go:** +### **Go:** (版本一)左闭右闭区间 @@ -288,7 +288,7 @@ func search(nums []int, target int) int { } ``` -**JavaScript:** +### **JavaScript:** (版本一)左闭右闭区间 [left, right] ```js @@ -345,7 +345,7 @@ var search = function(nums, target) { }; ``` -**TypeScript** +### **TypeScript** (版本一)左闭右闭区间 @@ -387,7 +387,7 @@ function search(nums: number[], target: number): number { }; ``` -**Ruby:** +### **Ruby:** ```ruby # (版本一)左闭右闭区间 @@ -425,7 +425,7 @@ def search(nums, target) end ``` -**Swift:** +### **Swift:** ```swift // (版本一)左闭右闭区间 @@ -479,7 +479,7 @@ func search(nums: [Int], target: Int) -> Int { ``` -**Rust:** +### **Rust:** ```rust # (版本一)左闭右闭区间 @@ -523,7 +523,8 @@ impl Solution { } ``` -**C:** +### **C:** + ```c // (版本一) 左闭右闭区间 [left, right] int search(int* nums, int numsSize, int target){ @@ -575,7 +576,8 @@ int search(int* nums, int numsSize, int target){ } ``` -**PHP:** +### **PHP:** + ```php // 左闭右闭区间 class Solution { @@ -607,7 +609,8 @@ class Solution { } ``` -**C#:** +### **C#:** + ```csharp //左闭右闭 public class Solution { @@ -652,7 +655,8 @@ public class Solution{ } ``` -**Kotlin:** +### **Kotlin:** + ```kotlin class Solution { fun search(nums: IntArray, target: Int): Int { @@ -682,9 +686,8 @@ class Solution { } ``` +### **Kotlin:** - -**Kotlin:** ```Kotlin // (版本一)左闭右开区间 class Solution { @@ -715,7 +718,7 @@ class Solution { } } ``` -**Scala:** +### **Scala:** (版本一)左闭右闭区间 ```scala @@ -763,3 +766,4 @@ object Solution { + From 948aca860da277d744c9fb130039fe96dd79491f Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Mon, 17 Jul 2023 14:59:20 +0800 Subject: [PATCH 11/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200704.=E4=BA=8C?= =?UTF-8?q?=E5=88=86=E6=9F=A5=E6=89=BE=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0704.二分查找.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index d202dfa1..52abf578 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -5,7 +5,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

-## 704. 二分查找 +# 704. 二分查找 [力扣题目链接](https://leetcode.cn/problems/binary-search/) @@ -766,4 +766,3 @@ object Solution { - From fdbc7442ac2b685414544f0af79d64c40da05d0f Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Mon, 17 Jul 2023 15:11:55 +0800 Subject: [PATCH 12/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20027.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E5=85=83=E7=B4=A0=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0027.移除元素.md | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 3d43a199..ce9eccf0 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -5,7 +5,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

-## 27. 移除元素 +# 27. 移除元素 [力扣题目链接](https://leetcode.cn/problems/remove-element/) @@ -159,8 +159,8 @@ public: ## 其他语言版本 +### Java: -Java: ```java class Solution { public int removeElement(int[] nums, int val) { @@ -197,7 +197,7 @@ class Solution { } ``` -Python: +### Python: ``` python 3 @@ -233,8 +233,8 @@ class Solution: ``` +### Go: -Go: ```go func removeElement(nums []int, val int) int { length:=len(nums) @@ -275,7 +275,8 @@ func removeElement(nums []int, val int) int { } ``` -JavaScript: +### JavaScript: + ```javascript //时间复杂度:O(n) //空间复杂度:O(1) @@ -290,7 +291,7 @@ var removeElement = (nums, val) => { }; ``` -TypeScript: +### TypeScript: ```typescript function removeElement(nums: number[], val: number): number { @@ -305,7 +306,7 @@ function removeElement(nums: number[], val: number): number { }; ``` -Ruby: +### Ruby: ```ruby def remove_element(nums, val) @@ -319,7 +320,8 @@ def remove_element(nums, val) i end ``` -Rust: +### Rust: + ```rust impl Solution { pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { @@ -335,7 +337,7 @@ impl Solution { } ``` -Swift: +### Swift: ```swift func removeElement(_ nums: inout [Int], _ val: Int) -> Int { @@ -351,7 +353,8 @@ func removeElement(_ nums: inout [Int], _ val: Int) -> Int { } ``` -PHP: +### PHP: + ```php class Solution { /** @@ -375,7 +378,8 @@ class Solution { } ``` -C: +### C: + ```c int removeElement(int* nums, int numsSize, int val){ int slow = 0; @@ -391,7 +395,8 @@ int removeElement(int* nums, int numsSize, int val){ } ``` -Kotlin: +### Kotlin: + ```kotlin fun removeElement(nums: IntArray, `val`: Int): Int { var slowIndex = 0 // 初始化慢指针 @@ -402,7 +407,8 @@ fun removeElement(nums: IntArray, `val`: Int): Int { } ``` -Scala: +### Scala: + ```scala object Solution { def removeElement(nums: Array[Int], `val`: Int): Int = { @@ -418,7 +424,8 @@ object Solution { } ``` -C#: +### C#: + ```csharp public class Solution { public int RemoveElement(int[] nums, int val) { From ec101bebb24b9af7910c02b979b198c238ae12b1 Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Mon, 17 Jul 2023 15:21:00 +0800 Subject: [PATCH 13/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200977.=E6=9C=89?= =?UTF-8?q?=E5=BA=8F=E6=95=B0=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 42 +++++++++++++++----------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index de06c419..4bee585b 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -21,14 +21,14 @@ * 输入:nums = [-7,-3,2,3,11] * 输出:[4,9,9,49,121] -# 算法公开课 +## 算法公开课 **[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[双指针法经典题目!LeetCode:977.有序数组的平方](https://www.bilibili.com/video/BV1QB4y1D7ep),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 -# 思路 +## 思路 -## 暴力排序 +### 暴力排序 最直观的想法,莫过于:每个数平方之后,排个序,美滋滋,代码如下: @@ -47,7 +47,7 @@ public: 这个时间复杂度是 O(n + nlogn), 可以说是O(nlogn)的时间复杂度,但为了和下面双指针法算法时间复杂度有鲜明对比,我记为 O(n + nlog n)。 -## 双指针法 +### 双指针法 数组其实是有序的, 只不过负数平方之后可能成为最大数了。 @@ -99,7 +99,8 @@ public: ## 其他语言版本 -Java: +### Java: + ```Java class Solution { public int[] sortedSquares(int[] nums) { @@ -141,7 +142,8 @@ class Solution { } ``` -Python: +### Python: + ```Python (版本一)双指针法 class Solution: @@ -176,7 +178,8 @@ class Solution: return sorted(x*x for x in nums) ``` -Go: +### Go: + ```Go func sortedSquares(nums []int) []int { n := len(nums) @@ -196,7 +199,8 @@ func sortedSquares(nums []int) []int { return ans } ``` -Rust +### Rust: + ```rust impl Solution { pub fn sorted_squares(nums: Vec) -> Vec { @@ -217,7 +221,8 @@ impl Solution { } } ``` -Javascript: +### Javascript: + ```Javascript /** * @param {number[]} nums @@ -242,7 +247,7 @@ var sortedSquares = function(nums) { }; ``` -Typescript: +### Typescript: 双指针法: @@ -277,7 +282,7 @@ function sortedSquares(nums: number[]): number[] { }; ``` -Swift: +### Swift: ```swift func sortedSquares(_ nums: [Int]) -> [Int] { @@ -305,7 +310,7 @@ func sortedSquares(_ nums: [Int]) -> [Int] { } ``` -Ruby: +### Ruby: ```ruby def sorted_squares(nums) @@ -323,8 +328,8 @@ def sorted_squares(nums) end ``` +### C: -C: ```c int* sortedSquares(int* nums, int numsSize, int* returnSize){ //返回的数组大小就是原数组大小 @@ -357,7 +362,8 @@ int* sortedSquares(int* nums, int numsSize, int* returnSize){ } ``` -PHP: +### PHP: + ```php class Solution { /** @@ -386,7 +392,7 @@ class Solution { } ``` -Kotlin: +### Kotlin: 双指针法 ```kotlin @@ -437,7 +443,7 @@ class Solution { } ``` -Scala: +### Scala: 双指针: ```scala @@ -473,7 +479,8 @@ object Solution { } ``` -C#: +### C#: + ```csharp public class Solution { public int[] SortedSquares(int[] nums) { @@ -504,3 +511,4 @@ public class Solution { + From 76c84efca0bcfab9e889bf97458dd6b6423e0f05 Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Mon, 17 Jul 2023 15:32:24 +0800 Subject: [PATCH 14/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200209.=20=E9=95=BF?= =?UTF-8?q?=E5=BA=A6=E6=9C=80=E5=B0=8F=E7=9A=84=E5=AD=90=E6=95=B0=E7=BB=84?= =?UTF-8?q?=20=E6=8E=92=E7=89=88=E6=A0=BC=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0209.长度最小的子数组.md | 41 +++++++++++++---------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 82d551ea..4b1d0e96 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -23,14 +23,14 @@ * 1 <= nums.length <= 10^5 * 1 <= nums[i] <= 10^5 -# 算法公开课 +## 算法公开课 **[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[拿下滑动窗口! | LeetCode 209 长度最小的子数组](https://www.bilibili.com/video/BV1tZ4y1q7XE),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 -# 思路 +## 思路 -## 暴力解法 +### 暴力解法 这道题目暴力解法当然是 两个for循环,然后不断的寻找符合条件的子序列,时间复杂度很明显是O(n^2)。 @@ -64,7 +64,7 @@ public: 后面力扣更新了数据,暴力解法已经超时了。 -## 滑动窗口 +### 滑动窗口 接下来就开始介绍数组操作中另一个重要的方法:**滑动窗口**。 @@ -151,8 +151,8 @@ public: ## 其他语言版本 +### Java: -Java: ```java class Solution { @@ -173,7 +173,7 @@ class Solution { } ``` -Python: +### Python: ```python (版本一)滑动窗口法 @@ -216,7 +216,8 @@ class Solution: return min_len if min_len != float('inf') else 0 ``` -Go: +### Go: + ```go func minSubArrayLen(target int, nums []int) int { i := 0 @@ -242,8 +243,7 @@ func minSubArrayLen(target int, nums []int) int { } ``` - -JavaScript: +### JavaScript: ```js var minSubArrayLen = function(target, nums) { @@ -266,7 +266,7 @@ var minSubArrayLen = function(target, nums) { }; ``` -Typescript: +### Typescript: ```typescript function minSubArrayLen(target: number, nums: number[]): number { @@ -288,7 +288,7 @@ function minSubArrayLen(target: number, nums: number[]): number { }; ``` -Swift: +### Swift: ```swift func minSubArrayLen(_ target: Int, _ nums: [Int]) -> Int { @@ -309,7 +309,7 @@ func minSubArrayLen(_ target: Int, _ nums: [Int]) -> Int { } ``` -Rust: +### Rust: ```rust impl Solution { @@ -336,7 +336,8 @@ impl Solution { } ``` -PHP: +### PHP: + ```php // 双指针 - 滑动窗口 class Solution { @@ -365,7 +366,7 @@ class Solution { } ``` -Ruby: +### Ruby: ```ruby def min_sub_array_len(target, nums) @@ -383,8 +384,9 @@ def min_sub_array_len(target, nums) end ``` -C: +### C: 暴力解法: + ```c int minSubArrayLen(int target, int* nums, int numsSize){ //初始化最小长度为INT_MAX @@ -433,7 +435,8 @@ int minSubArrayLen(int target, int* nums, int numsSize){ } ``` -Kotlin: +### Kotlin: + ```kotlin class Solution { fun minSubArrayLen(target: Int, nums: IntArray): Int { @@ -485,7 +488,7 @@ class Solution { } } ``` -Scala: +### Scala: 滑动窗口: ```scala @@ -533,7 +536,8 @@ object Solution { } } ``` -C#: +### C#: + ```csharp public class Solution { public int MinSubArrayLen(int s, int[] nums) { @@ -559,3 +563,4 @@ public class Solution { + From 7a30d500cb5f328c3e4c952f2f9ae0ecb3382b45 Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Mon, 17 Jul 2023 15:47:48 +0800 Subject: [PATCH 15/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20059.=E8=9E=BA?= =?UTF-8?q?=E6=97=8B=E7=9F=A9=E9=98=B5II=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0059.螺旋矩阵II.md | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index fd40f3fc..f03fcdad 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -26,7 +26,7 @@ ## 算法公开课 **[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[拿下螺旋矩阵!LeetCode:59.螺旋矩阵II](https://www.bilibili.com/video/BV1SL4y1N7mV),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 - + ## 思路 这道题目可以说在面试中出现频率较高的题目,**本题并不涉及到什么算法,就是模拟过程,但却十分考察对代码的掌控能力。** @@ -125,15 +125,15 @@ public: ## 类似题目 -* 54.螺旋矩阵 -* 剑指Offer 29.顺时针打印矩阵 +* [54.螺旋矩阵](https://leetcode.cn/problems/spiral-matrix/) +* [剑指Offer 29.顺时针打印矩阵](https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/) ## 其他语言版本 -Java: +### Java: ```Java class Solution { @@ -176,7 +176,7 @@ class Solution { } ``` -python3: +### python3: ```python class Solution: @@ -207,7 +207,7 @@ class Solution: return nums ``` -javaScript +### JavaScript: ```javascript @@ -259,7 +259,7 @@ var generateMatrix = function(n) { ``` -TypeScript: +### TypeScript: ```typescript function generateMatrix(n: number): number[][] { @@ -304,7 +304,7 @@ function generateMatrix(n: number): number[][] { }; ``` -Go: +### Go: ```go package main @@ -397,7 +397,7 @@ func generateMatrix(n int) [][]int { } ``` -Swift: +### Swift: ```swift func generateMatrix(_ n: Int) -> [[Int]] { @@ -453,7 +453,7 @@ func generateMatrix(_ n: Int) -> [[Int]] { } ``` -Rust: +### Rust: ```rust impl Solution { @@ -506,7 +506,8 @@ impl Solution { } ``` -PHP: +### PHP: + ```php class Solution { /** @@ -548,7 +549,8 @@ class Solution { } ``` -C: +### C: + ```c int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){ //初始化返回的结果数组的大小 @@ -607,7 +609,8 @@ int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){ return ans; } ``` -Scala: +### Scala: + ```scala object Solution { def generateMatrix(n: Int): Array[Array[Int]] = { @@ -659,7 +662,8 @@ object Solution { } } ``` -C#: +### C#: + ```csharp public class Solution { public int[][] GenerateMatrix(int n) { @@ -688,3 +692,4 @@ public class Solution { + From 053632c31d05cae6391b29db2ec76f1945eb2cfe Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Mon, 17 Jul 2023 15:51:53 +0800 Subject: [PATCH 16/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E6=80=BB=E7=BB=93=E7=AF=87=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/数组总结篇.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/problems/数组总结篇.md b/problems/数组总结篇.md index ef962187..7550ce02 100644 --- a/problems/数组总结篇.md +++ b/problems/数组总结篇.md @@ -4,9 +4,9 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+# 数组总结篇 - -# 数组理论基础 +## 数组理论基础 数组是非常基础的数据结构,在面试中,考察数组的题目一般在思维上都不难,主要是考察对代码的掌控能力 @@ -51,7 +51,7 @@ 所以**Java的二维数组在内存中不是 `3*4` 的连续地址空间,而是四条连续的地址空间组成!** -# 数组的经典题目 +## 数组的经典题目 在面试中,数组是必考的基础数据结构。 @@ -59,7 +59,7 @@ 我们之前一共讲解了四道经典数组题目,每一道题目都代表一个类型,一种思想。 -## 二分法 +### 二分法 [数组:每次遇到二分法,都是一看就会,一写就废](https://programmercarl.com/0704.二分查找.html) @@ -75,7 +75,7 @@ **二分法是算法面试中的常考题,建议通过这道题目,锻炼自己手撕二分的能力**。 -## 双指针法 +### 双指针法 * [数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html) @@ -91,7 +91,7 @@ 双指针法(快慢指针法)在数组和链表的操作中是非常常见的,很多考察数组和链表操作的面试题,都使用双指针法。 -## 滑动窗口 +### 滑动窗口 * [数组:滑动窗口拯救了你](https://programmercarl.com/0209.长度最小的子数组.html) @@ -107,7 +107,7 @@ 如果没有接触过这一类的方法,很难想到类似的解题思路,滑动窗口方法还是很巧妙的。 -## 模拟行为 +### 模拟行为 * [数组:这个循环可以转懵很多人!](https://programmercarl.com/0059.螺旋矩阵II.html) @@ -118,7 +118,7 @@ 相信大家有遇到过这种情况: 感觉题目的边界调节超多,一波接着一波的判断,找边界,拆了东墙补西墙,好不容易运行通过了,代码写的十分冗余,毫无章法,其实**真正解决题目的代码都是简洁的,或者有原则性的**,大家可以在这道题目中体会到这一点。 -# 总结 +## 总结 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/数组总结.png) From a3cc34ef7413e7e80420674bd261e4de393f152c Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Mon, 17 Jul 2023 15:53:46 +0800 Subject: [PATCH 17/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=20=E6=8E=92=E7=89=88?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=BF=AE=E5=A4=8D?= 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 67b7b20d..d104c883 100644 --- a/problems/数组理论基础.md +++ b/problems/数组理论基础.md @@ -6,7 +6,7 @@ -## 数组理论基础 +# 数组理论基础 数组是非常基础的数据结构,在面试中,考察数组的题目一般在思维上都不难,主要是考察对代码的掌控能力 From b51a1d89bf6b340f3a96ba7f109c1d481a887693 Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Tue, 18 Jul 2023 14:21:20 +0800 Subject: [PATCH 18/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=20=E6=8E=92=E7=89=88?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/链表理论基础.md | 36 +++++++++++++++++----------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/problems/链表理论基础.md b/problems/链表理论基础.md index a09974df..da5a1b02 100644 --- a/problems/链表理论基础.md +++ b/problems/链表理论基础.md @@ -16,15 +16,15 @@ 如图所示: ![链表1](https://code-thinking-1253855093.file.myqcloud.com/pics/20200806194529815.png) -# 链表的类型 +## 链表的类型 接下来说一下链表的几种类型: -## 单链表 +### 单链表 刚刚说的就是单链表。 -## 双链表 +### 双链表 单链表中的指针域只能指向节点的下一个节点。 @@ -35,7 +35,7 @@ 如图所示: ![链表2](https://code-thinking-1253855093.file.myqcloud.com/pics/20200806194559317.png) -## 循环链表 +### 循环链表 循环链表,顾名思义,就是链表首尾相连。 @@ -44,7 +44,7 @@ ![链表4](https://code-thinking-1253855093.file.myqcloud.com/pics/20200806194629603.png) -# 链表的存储方式 +## 链表的存储方式 了解完链表的类型,再来说一说链表在内存中的存储方式。 @@ -60,7 +60,7 @@ 这个链表起始节点为2, 终止节点为7, 各个节点分布在内存的不同地址空间上,通过指针串联在一起。 -# 链表的定义 +## 链表的定义 接下来说一说链表的定义。 @@ -100,9 +100,9 @@ head->val = 5; 所以如果不定义构造函数使用默认构造函数的话,在初始化的时候就不能直接给变量赋值! -# 链表的操作 +## 链表的操作 -## 删除节点 +### 删除节点 删除D节点,如图所示: @@ -116,7 +116,7 @@ head->val = 5; 其他语言例如Java、Python,就有自己的内存回收机制,就不用自己手动释放了。 -## 添加节点 +### 添加节点 如图所示: @@ -126,7 +126,7 @@ head->val = 5; 但是要注意,要是删除第五个节点,需要从头节点查找到第四个节点通过next指针进行删除操作,查找的时间复杂度是O(n)。 -# 性能分析 +## 性能分析 再把链表的特性和数组的特性进行一个对比,如图所示: @@ -143,8 +143,7 @@ head->val = 5; ## 其他语言版本 - -Java: +### Java: ```java public class ListNode { @@ -171,7 +170,7 @@ public class ListNode { } ``` -JavaScript: +### JavaScript: ```javascript class ListNode { @@ -184,7 +183,7 @@ class ListNode { } ``` -TypeScript: +### TypeScript: ```typescript class ListNode { @@ -197,7 +196,7 @@ class ListNode { } ``` -Python: +### Python: ```python class ListNode: @@ -206,7 +205,7 @@ class ListNode: self.next = next ``` -Go: +### Go: ```go type ListNode struct { @@ -215,7 +214,7 @@ type ListNode struct { } ``` -Scala: +### Scala: ```scala class ListNode(_x: Int = 0, _next: ListNode = null) { @@ -224,7 +223,7 @@ class ListNode(_x: Int = 0, _next: ListNode = null) { } ``` -Rust: +### Rust: ```rust #[derive(PartialEq, Eq, Clone, Debug)] @@ -246,3 +245,4 @@ impl ListNode { + From a78116889f705d9e7f72f927decb0a9e844bd807 Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Tue, 18 Jul 2023 14:28:12 +0800 Subject: [PATCH 19/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200203.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0=20=E6=8E=92?= =?UTF-8?q?=E7=89=88=E6=A0=BC=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 33 ++++++++++++++--------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 300f98e9..f09c572b 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -27,14 +27,12 @@ 输入:head = [7,7,7,7], val = 7 输出:[] -# 算法公开课 +## 算法公开课 **[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[链表基础操作| LeetCode:203.移除链表元素](https://www.bilibili.com/video/BV18B4y1s7R9),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 -# 思路 - -为了方便大家理解,我特意录制了视频:[链表基础操作| LeetCode:203.移除链表元素](https://www.bilibili.com/video/BV18B4y1s7R9),结合视频在看本题解,事半功倍。 +## 思路 这里以链表 1 4 2 4 来举例,移除元素4。 @@ -91,7 +89,7 @@ 最后呢在题目中,return 头结点的时候,别忘了 `return dummyNode->next;`, 这才是新的头结点 -# C++代码 +### C++代码 **直接使用原来的链表来进行移除节点操作:** @@ -159,7 +157,7 @@ public: ## 其他语言版本 -C: +### C: 用原来的链表操作: ```c @@ -227,7 +225,7 @@ struct ListNode* removeElements(struct ListNode* head, int val){ } ``` -Java: +### Java: ```java /** @@ -308,7 +306,7 @@ public ListNode removeElements(ListNode head, int val) { } ``` -Python: +### Python: ```python (版本一)虚拟头节点法 @@ -334,7 +332,7 @@ class Solution: ``` -Go: +### Go: ```go /** @@ -359,7 +357,7 @@ func removeElements(head *ListNode, val int) *ListNode { } ``` -javaScript: +### JavaScript: ```js /** @@ -381,7 +379,7 @@ var removeElements = function(head, val) { }; ``` -TypeScript: +### TypeScript: 版本一(在原链表上直接删除): @@ -437,7 +435,7 @@ function removeElements(head: ListNode | null, val: number): ListNode | null { }; ``` -Swift: +### Swift: ```swift /** @@ -465,7 +463,7 @@ func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? { } ``` -PHP: +### PHP: ```php /** @@ -493,7 +491,7 @@ func removeElements(head *ListNode, val int) *ListNode { } ``` -RUST: +### Rust: ```rust // Definition for singly-linked list. @@ -531,7 +529,7 @@ impl Solution { } ``` -Scala: +### Scala: ```scala /** @@ -564,7 +562,7 @@ object Solution { } ``` -Kotlin: +### Kotlin: ```kotlin /** @@ -600,7 +598,8 @@ class Solution { } ``` -C# +### C# + ```CSharp /** * Definition for singly-linked list. From 61366ff59037d5f22f256e5bc410efd8a36a35d3 Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Tue, 18 Jul 2023 14:41:02 +0800 Subject: [PATCH 20/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200707.=E8=AE=BE?= =?UTF-8?q?=E8=AE=A1=E9=93=BE=E8=A1=A8=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 4 +--- problems/0707.设计链表.md | 34 +++++++++++++++-------------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index f09c572b..c8f802a1 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -88,9 +88,6 @@ 最后呢在题目中,return 头结点的时候,别忘了 `return dummyNode->next;`, 这才是新的头结点 - -### C++代码 - **直接使用原来的链表来进行移除节点操作:** ```CPP @@ -638,3 +635,4 @@ public class Solution + diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 3f096a22..c27f0107 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -25,12 +25,12 @@ ![707示例](https://code-thinking-1253855093.file.myqcloud.com/pics/20200814200558953.png) -# 算法公开课 +## 算法公开课 **[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[帮你把链表操作学个通透!LeetCode:707.设计链表](https://www.bilibili.com/video/BV1FU4y1X7WD),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 -# 思路 +## 思路 如果对链表的基础知识还不太懂,可以看这篇文章:[关于链表,你该了解这些!](https://programmercarl.com/链表理论基础.html) @@ -58,8 +58,6 @@ 下面采用的设置一个虚拟头结点(这样更方便一些,大家看代码就会感受出来)。 - -## 代码 ```CPP class MyLinkedList { public: @@ -167,7 +165,8 @@ private: ## 其他语言版本 -C: +### C: + ```C typedef struct MyLinkedList { int val; @@ -291,7 +290,8 @@ void myLinkedListFree(MyLinkedList* obj) { */ ``` -Java: +### Java: + ```Java //单链表 class ListNode { @@ -487,7 +487,8 @@ class MyLinkedList { */ ``` -Python: +### Python: + ```python (版本一)单链表法 class ListNode: @@ -661,7 +662,7 @@ class MyLinkedList: # obj.deleteAtIndex(index) ``` -Go: +### Go: ```go //单链表实现 @@ -915,7 +916,7 @@ func (this *MyLinkedList) DeleteAtIndex(index int) { } ``` -javaScript: +### JavaScript: ```js @@ -1055,7 +1056,8 @@ MyLinkedList.prototype.deleteAtIndex = function(index) { */ ``` -TypeScript: +### TypeScript: + ```TypeScript class ListNode { public val: number; @@ -1173,7 +1175,8 @@ class MyLinkedList { } ``` -Kotlin: +### Kotlin: + ```kotlin class MyLinkedList { @@ -1241,8 +1244,7 @@ class MyLinkedList { } ``` - -Swift: +### Swift: ```swift class MyLinkedList { @@ -1323,7 +1325,8 @@ class MyLinkedList { } ``` -Scala: +### Scala: + ```scala class ListNode(_x: Int = 0, _next: ListNode = null) { var next: ListNode = _next @@ -1393,7 +1396,7 @@ class MyLinkedList() { } ``` -Rust: +### Rust: ```rust #[derive(Debug)] @@ -1486,4 +1489,3 @@ impl MyLinkedList { - From 32bf073bc8c2fe08aabc9aaf0ef61184febfb0a8 Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Tue, 18 Jul 2023 14:50:44 +0800 Subject: [PATCH 21/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200206.=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E9=93=BE=E8=A1=A8=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0206.反转链表.md | 745 ++++++++++++++++++++++++++++++++++ problems/0206.翻转链表.md | 55 ++- 2 files changed, 772 insertions(+), 28 deletions(-) create mode 100644 problems/0206.反转链表.md diff --git a/problems/0206.反转链表.md b/problems/0206.反转链表.md new file mode 100644 index 00000000..5a57939a --- /dev/null +++ b/problems/0206.反转链表.md @@ -0,0 +1,745 @@ +

+ + + +

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+ + +> 反转链表的写法很简单,一些同学甚至可以背下来但过一阵就忘了该咋写,主要是因为没有理解真正的反转过程。 + +# 206.反转链表 + +[力扣题目链接](https://leetcode.cn/problems/reverse-linked-list/) + +题意:反转一个单链表。 + +示例: +输入: 1->2->3->4->5->NULL +输出: 5->4->3->2->1->NULL + +## 算法公开课 + +**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[帮你拿下反转链表 | LeetCode:206.反转链表](https://www.bilibili.com/video/BV1nB4y1i7eL),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + + +## 思路 + +如果再定义一个新的链表,实现链表元素的反转,其实这是对内存空间的浪费。 + +其实只需要改变链表的next指针的指向,直接将链表反转 ,而不用重新定义一个新的链表,如图所示: + + +![206_反转链表](https://code-thinking-1253855093.file.myqcloud.com/pics/20210218090901207.png) + +之前链表的头节点是元素1, 反转之后头结点就是元素5 ,这里并没有添加或者删除节点,仅仅是改变next指针的方向。 + +那么接下来看一看是如何反转的呢? + +我们拿有示例中的链表来举例,如动画所示:(纠正:动画应该是先移动pre,在移动cur) + +![](https://code-thinking.cdn.bcebos.com/gifs/206.%E7%BF%BB%E8%BD%AC%E9%93%BE%E8%A1%A8.gif) + +首先定义一个cur指针,指向头结点,再定义一个pre指针,初始化为null。 + +然后就要开始反转了,首先要把 cur->next 节点用tmp指针保存一下,也就是保存一下这个节点。 + +为什么要保存一下这个节点呢,因为接下来要改变 cur->next 的指向了,将cur->next 指向pre ,此时已经反转了第一个节点了。 + +接下来,就是循环走如下代码逻辑了,继续移动pre和cur指针。 + +最后,cur 指针已经指向了null,循环结束,链表也反转完毕了。 此时我们return pre指针就可以了,pre指针就指向了新的头结点。 + +### 双指针法 +```CPP +class Solution { +public: + ListNode* reverseList(ListNode* head) { + ListNode* temp; // 保存cur的下一个节点 + ListNode* cur = head; + ListNode* pre = NULL; + while(cur) { + temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next + cur->next = pre; // 翻转操作 + // 更新pre 和 cur指针 + pre = cur; + cur = temp; + } + return pre; + } +}; +``` + +* 时间复杂度: O(n) +* 空间复杂度: O(1) + +### 递归法 + +递归法相对抽象一些,但是其实和双指针法是一样的逻辑,同样是当cur为空的时候循环结束,不断将cur指向pre的过程。 + +关键是初始化的地方,可能有的同学会不理解, 可以看到双指针法中初始化 cur = head,pre = NULL,在递归法中可以从如下代码看出初始化的逻辑也是一样的,只不过写法变了。 + +具体可以看代码(已经详细注释),**双指针法写出来之后,理解如下递归写法就不难了,代码逻辑都是一样的。** +```CPP +class Solution { +public: + ListNode* reverse(ListNode* pre,ListNode* cur){ + if(cur == NULL) return pre; + ListNode* temp = cur->next; + cur->next = pre; + // 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步 + // pre = cur; + // cur = temp; + return reverse(cur,temp); + } + ListNode* reverseList(ListNode* head) { + // 和双指针法初始化是一样的逻辑 + // ListNode* cur = head; + // ListNode* pre = NULL; + return reverse(NULL, head); + } + +}; +``` + +* 时间复杂度: O(n), 要递归处理链表的每个节点 +* 空间复杂度: O(n), 递归调用了 n 层栈空间 + +我们可以发现,上面的递归写法和双指针法实质上都是从前往后翻转指针指向,其实还有另外一种与双指针法不同思路的递归写法:从后往前翻转指针指向。 + +具体代码如下(带详细注释): + +```CPP +class Solution { +public: + ListNode* reverseList(ListNode* head) { + // 边缘条件判断 + if(head == NULL) return NULL; + if (head->next == NULL) return head; + + // 递归调用,翻转第二个节点开始往后的链表 + ListNode *last = reverseList(head->next); + // 翻转头节点与第二个节点的指向 + head->next->next = head; + // 此时的 head 节点为尾节点,next 需要指向 NULL + head->next = NULL; + return last; + } +}; +``` + +* 时间复杂度: O(n) +* 空间复杂度: O(n) + + +## 其他语言版本 + +### Java: + +```java +// 双指针 +class Solution { + public ListNode reverseList(ListNode head) { + ListNode prev = null; + ListNode cur = head; + ListNode temp = null; + while (cur != null) { + temp = cur.next;// 保存下一个节点 + cur.next = prev; + prev = cur; + cur = temp; + } + return prev; + } +} +``` + +```java +// 递归 +class Solution { + public ListNode reverseList(ListNode head) { + return reverse(null, head); + } + + private ListNode reverse(ListNode prev, ListNode cur) { + if (cur == null) { + return prev; + } + ListNode temp = null; + temp = cur.next;// 先保存下一个节点 + cur.next = prev;// 反转 + // 更新prev、cur位置 + // prev = cur; + // cur = temp; + return reverse(cur, temp); + } +} +``` + +```java +// 从后向前递归 +class Solution { + ListNode reverseList(ListNode head) { + // 边缘条件判断 + if(head == null) return null; + if (head.next == null) return head; + + // 递归调用,翻转第二个节点开始往后的链表 + ListNode last = reverseList(head.next); + // 翻转头节点与第二个节点的指向 + head.next.next = head; + // 此时的 head 节点为尾节点,next 需要指向 NULL + head.next = null; + return last; + } +} +``` + +### Python: + +```python +(版本一)双指针法 +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + cur = head + pre = None + while cur: + temp = cur.next # 保存一下 cur的下一个节点,因为接下来要改变cur->next + cur.next = pre #反转 + #更新pre、cur指针 + pre = cur + cur = temp + return pre +``` + +```python +(版本二)递归法 +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + return self.reverse(head, None) + def reverse(self, cur: ListNode, pre: ListNode) -> ListNode: + if cur == None: + return pre + temp = cur.next + cur.next = pre + return self.reverse(temp, cur) + +``` + + + +### Go: + +```go +//双指针 +func reverseList(head *ListNode) *ListNode { + var pre *ListNode + cur := head + for cur != nil { + next := cur.Next + cur.Next = pre + pre = cur + cur = next + } + return pre +} + +//递归 +func reverseList(head *ListNode) *ListNode { + return help(nil, head) +} + +func help(pre, head *ListNode)*ListNode{ + if head == nil { + return pre + } + next := head.Next + head.Next = pre + return help(head, next) +} + +``` +### JavaScript: + +```js +/** + * @param {ListNode} head + * @return {ListNode} + */ + +// 双指针: +var reverseList = function(head) { + if(!head || !head.next) return head; + let temp = null, pre = null, cur = head; + while(cur) { + temp = cur.next; + cur.next = pre; + pre = cur; + cur = temp; + } + // temp = cur = null; + return pre; +}; + +// 递归: +var reverse = function(pre, head) { + if(!head) return pre; + const temp = head.next; + head.next = pre; + pre = head + return reverse(pre, temp); +} + +var reverseList = function(head) { + return reverse(null, head); +}; + +// 递归2 +var reverse = function(head) { + if(!head || !head.next) return head; + // 从后往前翻 + const pre = reverse(head.next); + head.next = pre.next; + pre.next = head; + return head; +} + +var reverseList = function(head) { + let cur = head; + while(cur && cur.next) { + cur = cur.next; + } + reverse(head); + return cur; +}; +``` + +### TypeScript: + +```typescript +// 双指针法 +function reverseList(head: ListNode | null): ListNode | null { + let preNode: ListNode | null = null, + curNode: ListNode | null = head, + tempNode: ListNode | null; + while (curNode) { + tempNode = curNode.next; + curNode.next = preNode; + preNode = curNode; + curNode = tempNode; + } + return preNode; +}; + +// 递归(从前往后翻转) +function reverseList(head: ListNode | null): ListNode | null { + function recur(preNode: ListNode | null, curNode: ListNode | null): ListNode | null { + if (curNode === null) return preNode; + let tempNode: ListNode | null = curNode.next; + curNode.next = preNode; + preNode = curNode; + curNode = tempNode; + return recur(preNode, curNode); + } + return recur(null, head); +}; + +// 递归(从后往前翻转) +function reverseList(head: ListNode | null): ListNode | null { + if (head === null) return null; + let newHead: ListNode | null; + function recur(node: ListNode | null, preNode: ListNode | null): void { + if (node.next === null) { + newHead = node; + newHead.next = preNode; + } else { + recur(node.next, node); + node.next = preNode; + } + } + recur(head, null); + return newHead; +}; +``` + +### Ruby: + +```ruby +# 双指针 +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +def reverse_list(head) + # return nil if head.nil? # 循环判断条件亦能起到相同作用因此不必单独判断 + cur, per = head, nil + until cur.nil? + tem = cur.next + cur.next = per + per = cur + cur = tem + end + per +end + +# 递归 +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +def reverse_list(head) + reverse(nil, head) +end + +def reverse(pre, cur) + return pre if cur.nil? + tem = cur.next + cur.next = pre + reverse(cur, tem) # 通过递归实现双指针法中的更新操作 +end +``` + +### Kotlin: + +```Kotlin +fun reverseList(head: ListNode?): ListNode? { + var pre: ListNode? = null + var cur = head + while (cur != null) { + val temp = cur.next + cur.next = pre + pre = cur + cur = temp + } + return pre +} +``` +```kotlin +/** + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +class Solution { + fun reverseList(head: ListNode?): ListNode? { + // temp用来存储临时的节点 + var temp: ListNode? + // cur用来遍历链表 + var cur: ListNode? = head + // pre用来作为链表反转的工具 + // pre是比pre前一位的节点 + var pre: ListNode? = null + while (cur != null) { + // 临时存储原本cur的下一个节点 + temp = cur.next + // 使cur下一节点地址为它之前的 + cur.next = pre + // 之后随着cur的遍历移动pre + pre = cur; + // 移动cur遍历链表各个节点 + cur = temp; + } + // 由于开头使用pre为null,所以cur等于链表本身长度+1, + // 此时pre在cur前一位,所以此时pre为头节点 + return pre; + } +} +``` + +### Swift: + +```swift +/// 双指针法 (迭代) +/// - Parameter head: 头结点 +/// - Returns: 翻转后的链表头结点 +func reverseList(_ head: ListNode?) -> ListNode? { + if head == nil || head?.next == nil { + return head + } + var pre: ListNode? = nil + var cur: ListNode? = head + var temp: ListNode? = nil + while cur != nil { + temp = cur?.next + cur?.next = pre + pre = cur + cur = temp + } + return pre +} + +/// 递归 +/// - Parameter head: 头结点 +/// - Returns: 翻转后的链表头结点 +func reverseList2(_ head: ListNode?) -> ListNode? { + return reverse(pre: nil, cur: head) +} +func reverse(pre: ListNode?, cur: ListNode?) -> ListNode? { + if cur == nil { + return pre + } + let temp: ListNode? = cur?.next + cur?.next = pre + return reverse(pre: cur, cur: temp) +} +``` + +### C: +双指针法: + +```c +struct ListNode* reverseList(struct ListNode* head){ + //保存cur的下一个结点 + struct ListNode* temp; + //pre指针指向前一个当前结点的前一个结点 + struct ListNode* pre = NULL; + //用head代替cur,也可以再定义一个cur结点指向head。 + while(head) { + //保存下一个结点的位置 + temp = head->next; + //翻转操作 + head->next = pre; + //更新结点 + pre = head; + head = temp; + } + return pre; +} +``` + +递归法: +```c +struct ListNode* reverse(struct ListNode* pre, struct ListNode* cur) { + if(!cur) + return pre; + struct ListNode* temp = cur->next; + cur->next = pre; + //将cur作为pre传入下一层 + //将temp作为cur传入下一层,改变其指针指向当前cur + return reverse(cur, temp); +} + +struct ListNode* reverseList(struct ListNode* head){ + return reverse(NULL, head); +} +``` + + + +### PHP: + +```php +// 双指针法: +function reverseList($head) { + $cur = $head; + $pre = NULL; + while($cur){ + $temp = $cur->next; + $cur->next = $pre; + $pre = $cur; + $cur = $temp; + } + return $pre; + } +``` + +### Scala: +双指针法: + +```scala +object Solution { + def reverseList(head: ListNode): ListNode = { + var pre: ListNode = null + var cur = head + while (cur != null) { + var tmp = cur.next + cur.next = pre + pre = cur + cur = tmp + } + pre + } +} +``` +递归法: +```scala +object Solution { + def reverseList(head: ListNode): ListNode = { + reverse(null, head) + } + + def reverse(pre: ListNode, cur: ListNode): ListNode = { + if (cur == null) { + return pre // 如果当前cur为空,则返回pre + } + val tmp: ListNode = cur.next + cur.next = pre + reverse(cur, tmp) // 此时cur成为前一个节点,tmp是当前节点 + } + +} +``` + +### Rust: +双指针法: + +```rust +impl Solution { + pub fn reverse_list(head: Option>) -> Option> { + let mut cur = head; + let mut pre = None; + while let Some(mut node) = cur.take() { + cur = node.next; + node.next = pre; + pre = Some(node); + } + pre + } +} +``` + +递归法: + +```rust +impl Solution { + pub fn reverse_list(head: Option>) -> Option> { + fn rev( + mut head: Option>, + mut pre: Option>, + ) -> Option> { + if let Some(mut node) = head.take() { + let cur = node.next; + node.next = pre; + pre = Some(node); + return rev(cur, pre); + } + pre + } + rev(head, None) + } +} +``` +### C#: +三指针法, 感觉会更直观: + +```cs +public LinkNumbers Reverse() +{ + ///用三指针,写的过程中能够弥补二指针在翻转过程中的想象 + LinkNumbers pre = null; + var move = root; + var next = root; + + while (next != null) + { + next = next.linknext; + move.linknext = pre; + pre = move; + move = next; + } + root = pre; + return root; +} + +///LinkNumbers的定义 +public class LinkNumbers +{ + /// + /// 链表值 + /// + public int value { get; set; } + + /// + /// 链表指针 + /// + public LinkNumbers linknext { get; set; } +} +``` + +## 其他解法 + +### 使用虚拟头结点解决链表反转 + +> 使用虚拟头结点,通过头插法实现链表的反转(不需要栈) + +```java +// 迭代方法:增加虚头结点,使用头插法实现链表翻转 +public static ListNode reverseList1(ListNode head) { + // 创建虚头结点 + ListNode dumpyHead = new ListNode(-1); + dumpyHead.next = null; + // 遍历所有节点 + ListNode cur = head; + while(cur != null){ + ListNode temp = cur.next; + // 头插法 + cur.next = dumpyHead.next; + dumpyHead.next = cur; + cur = temp; + } + return dumpyHead.next; +} +``` + + + +### 使用栈解决反转链表的问题 + +* 首先将所有的结点入栈 +* 然后创建一个虚拟虚拟头结点,让cur指向虚拟头结点。然后开始循环出栈,每出来一个元素,就把它加入到以虚拟头结点为头结点的链表当中,最后返回即可。 + +```java +public ListNode reverseList(ListNode head) { + // 如果链表为空,则返回空 + if (head == null) return null; + // 如果链表中只有只有一个元素,则直接返回 + if (head.next == null) return head; + // 创建栈 每一个结点都入栈 + Stack stack = new Stack<>(); + ListNode cur = head; + while (cur != null) { + stack.push(cur); + cur = cur.next; + } + // 创建一个虚拟头结点 + ListNode pHead = new ListNode(0); + cur = pHead; + while (!stack.isEmpty()) { + ListNode node = stack.pop(); + cur.next = node; + cur = cur.next; + } + // 最后一个元素的next要赋值为空 + cur.next = null; + return pHead.next; +} +``` + +> 采用这种方法需要注意一点。就是当整个出栈循环结束以后,cur正好指向原来链表的第一个结点,而此时结点1中的next指向的是结点2,因此最后还需要`cur.next = null` +![image-20230117195418626](https://raw.githubusercontent.com/liyuxuan7762/MyImageOSS/master/md_images/image-20230117195418626.png) + +

+ + + diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index c63c998d..5a57939a 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -17,14 +17,12 @@ 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL -# 算法公开课 +## 算法公开课 **[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[帮你拿下反转链表 | LeetCode:206.反转链表](https://www.bilibili.com/video/BV1nB4y1i7eL),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 -# 思路 - -本题我录制了B站视频,[帮你拿下反转链表 | LeetCode:206.反转链表](https://www.bilibili.com/video/BV1nB4y1i7eL),相信结合视频在看本篇题解,更有助于大家对链表的理解。 +## 思路 如果再定义一个新的链表,实现链表元素的反转,其实这是对内存空间的浪费。 @@ -51,9 +49,7 @@ 最后,cur 指针已经指向了null,循环结束,链表也反转完毕了。 此时我们return pre指针就可以了,pre指针就指向了新的头结点。 -# C++代码 - -## 双指针法 +### 双指针法 ```CPP class Solution { public: @@ -76,7 +72,7 @@ public: * 时间复杂度: O(n) * 空间复杂度: O(1) -## 递归法 +### 递归法 递归法相对抽象一些,但是其实和双指针法是一样的逻辑,同样是当cur为空的时候循环结束,不断将cur指向pre的过程。 @@ -137,8 +133,8 @@ public: ## 其他语言版本 +### Java: -Java: ```java // 双指针 class Solution { @@ -198,7 +194,8 @@ class Solution { } ``` -Python +### Python: + ```python (版本一)双指针法 # Definition for singly-linked list. @@ -219,8 +216,6 @@ class Solution: return pre ``` -Python递归法: - ```python (版本二)递归法 # Definition for singly-linked list. @@ -242,7 +237,7 @@ class Solution: -Go: +### Go: ```go //双指针 @@ -273,7 +268,7 @@ func help(pre, head *ListNode)*ListNode{ } ``` -javaScript: +### JavaScript: ```js /** @@ -328,7 +323,7 @@ var reverseList = function(head) { }; ``` -TypeScript: +### TypeScript: ```typescript // 双指针法 @@ -376,7 +371,7 @@ function reverseList(head: ListNode | null): ListNode | null { }; ``` -Ruby: +### Ruby: ```ruby # 双指针 @@ -421,7 +416,8 @@ def reverse(pre, cur) end ``` -Kotlin: +### Kotlin: + ```Kotlin fun reverseList(head: ListNode?): ListNode? { var pre: ListNode? = null @@ -471,7 +467,8 @@ class Solution { } ``` -Swift: +### Swift: + ```swift /// 双指针法 (迭代) /// - Parameter head: 头结点 @@ -508,8 +505,9 @@ func reverse(pre: ListNode?, cur: ListNode?) -> ListNode? { } ``` -C: +### C: 双指针法: + ```c struct ListNode* reverseList(struct ListNode* head){ //保存cur的下一个结点 @@ -549,7 +547,8 @@ struct ListNode* reverseList(struct ListNode* head){ -PHP: +### PHP: + ```php // 双指针法: function reverseList($head) { @@ -565,8 +564,9 @@ function reverseList($head) { } ``` -Scala: +### Scala: 双指针法: + ```scala object Solution { def reverseList(head: ListNode): ListNode = { @@ -601,7 +601,7 @@ object Solution { } ``` -Rust: +### Rust: 双指针法: ```rust @@ -640,7 +640,7 @@ impl Solution { } } ``` -C#: +### C#: 三指针法, 感觉会更直观: ```cs @@ -677,11 +677,11 @@ public class LinkNumbers } ``` +## 其他解法 +### 使用虚拟头结点解决链表反转 -## 使用虚拟头结点解决链表翻转 - -> 使用虚拟头结点,通过头插法实现链表的翻转(不需要栈) +> 使用虚拟头结点,通过头插法实现链表的反转(不需要栈) ```java // 迭代方法:增加虚头结点,使用头插法实现链表翻转 @@ -704,7 +704,7 @@ public static ListNode reverseList1(ListNode head) { -## 使用栈解决反转链表的问题 +### 使用栈解决反转链表的问题 * 首先将所有的结点入栈 * 然后创建一个虚拟虚拟头结点,让cur指向虚拟头结点。然后开始循环出栈,每出来一个元素,就把它加入到以虚拟头结点为头结点的链表当中,最后返回即可。 @@ -743,4 +743,3 @@ public ListNode reverseList(ListNode head) { - From 2acceb7474b60ad4aa16eef4b9bf94657ac85aeb Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Tue, 18 Jul 2023 15:00:29 +0800 Subject: [PATCH 22/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20024.=E4=B8=A4?= =?UTF-8?q?=E4=B8=A4=E4=BA=A4=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E8=8A=82=E7=82=B9=20=E6=8E=92=E7=89=88=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0024.两两交换链表中的节点.md | 37 +- problems/0206.反转链表.md | 745 ------------------ 2 files changed, 23 insertions(+), 759 deletions(-) delete mode 100644 problems/0206.反转链表.md diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index d7c03b64..c612c4b3 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -5,7 +5,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

-## 24. 两两交换链表中的节点 +# 24. 两两交换链表中的节点 [力扣题目链接](https://leetcode.cn/problems/swap-nodes-in-pairs/) @@ -16,9 +16,11 @@ 24.两两交换链表中的节点-题意 -## 思路 +## 算法公开课 -《代码随想录》算法公开课:[帮你把链表细节学清楚! | LeetCode:24. 两两交换链表中的节点](https://www.bilibili.com/video/BV1YT411g7br),相信结合视频在看本篇题解,更有助于大家对链表的理解。 +**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[帮你把链表细节学清楚! | LeetCode:24. 两两交换链表中的节点](https://www.bilibili.com/video/BV1YT411g7br),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 + +## 思路 这道题目正常模拟就可以了。 @@ -88,7 +90,8 @@ public: ## 其他语言版本 -C: +### C: + ```c /** * Definition for singly-linked list. @@ -132,7 +135,7 @@ struct ListNode* swapPairs(struct ListNode* head){ } ``` -Java: +### Java: ```Java // 递归版本 @@ -176,7 +179,8 @@ class Solution { } ``` -Python: +### Python: + ```python # 递归版本 # Definition for singly-linked list. @@ -226,7 +230,8 @@ class Solution: ``` -Go: +### Go: + ```go func swapPairs(head *ListNode) *ListNode { dummy := &ListNode{ @@ -262,7 +267,8 @@ func swapPairs(head *ListNode) *ListNode { } ``` -Javascript: +### Javascript: + ```javascript var swapPairs = function (head) { let ret = new ListNode(0, head), temp = ret; @@ -277,7 +283,7 @@ var swapPairs = function (head) { }; ``` -TypeScript: +### TypeScript: ```typescript function swapPairs(head: ListNode | null): ListNode | null { @@ -296,7 +302,7 @@ function swapPairs(head: ListNode | null): ListNode | null { }; ``` -Kotlin: +### Kotlin: ```kotlin fun swapPairs(head: ListNode?): ListNode? { @@ -316,7 +322,8 @@ fun swapPairs(head: ListNode?): ListNode? { } ``` -Swift: +### Swift: + ```swift func swapPairs(_ head: ListNode?) -> ListNode? { if head == nil || head?.next == nil { @@ -337,7 +344,8 @@ func swapPairs(_ head: ListNode?) -> ListNode? { return dummyHead.next } ``` -Scala: +### Scala: + ```scala // 虚拟头节点 object Solution { @@ -361,7 +369,8 @@ object Solution { } ``` -PHP: +### PHP: + ```php //虚拟头结点 function swapPairs($head) { @@ -404,7 +413,7 @@ function swapPairs($head) } ``` -Rust: +### Rust: ```rust // 虚拟头节点 diff --git a/problems/0206.反转链表.md b/problems/0206.反转链表.md deleted file mode 100644 index 5a57939a..00000000 --- a/problems/0206.反转链表.md +++ /dev/null @@ -1,745 +0,0 @@ -

- - - -

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- - -> 反转链表的写法很简单,一些同学甚至可以背下来但过一阵就忘了该咋写,主要是因为没有理解真正的反转过程。 - -# 206.反转链表 - -[力扣题目链接](https://leetcode.cn/problems/reverse-linked-list/) - -题意:反转一个单链表。 - -示例: -输入: 1->2->3->4->5->NULL -输出: 5->4->3->2->1->NULL - -## 算法公开课 - -**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[帮你拿下反转链表 | LeetCode:206.反转链表](https://www.bilibili.com/video/BV1nB4y1i7eL),相信结合视频再看本篇题解,更有助于大家对本题的理解**。 - - -## 思路 - -如果再定义一个新的链表,实现链表元素的反转,其实这是对内存空间的浪费。 - -其实只需要改变链表的next指针的指向,直接将链表反转 ,而不用重新定义一个新的链表,如图所示: - - -![206_反转链表](https://code-thinking-1253855093.file.myqcloud.com/pics/20210218090901207.png) - -之前链表的头节点是元素1, 反转之后头结点就是元素5 ,这里并没有添加或者删除节点,仅仅是改变next指针的方向。 - -那么接下来看一看是如何反转的呢? - -我们拿有示例中的链表来举例,如动画所示:(纠正:动画应该是先移动pre,在移动cur) - -![](https://code-thinking.cdn.bcebos.com/gifs/206.%E7%BF%BB%E8%BD%AC%E9%93%BE%E8%A1%A8.gif) - -首先定义一个cur指针,指向头结点,再定义一个pre指针,初始化为null。 - -然后就要开始反转了,首先要把 cur->next 节点用tmp指针保存一下,也就是保存一下这个节点。 - -为什么要保存一下这个节点呢,因为接下来要改变 cur->next 的指向了,将cur->next 指向pre ,此时已经反转了第一个节点了。 - -接下来,就是循环走如下代码逻辑了,继续移动pre和cur指针。 - -最后,cur 指针已经指向了null,循环结束,链表也反转完毕了。 此时我们return pre指针就可以了,pre指针就指向了新的头结点。 - -### 双指针法 -```CPP -class Solution { -public: - ListNode* reverseList(ListNode* head) { - ListNode* temp; // 保存cur的下一个节点 - ListNode* cur = head; - ListNode* pre = NULL; - while(cur) { - temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next - cur->next = pre; // 翻转操作 - // 更新pre 和 cur指针 - pre = cur; - cur = temp; - } - return pre; - } -}; -``` - -* 时间复杂度: O(n) -* 空间复杂度: O(1) - -### 递归法 - -递归法相对抽象一些,但是其实和双指针法是一样的逻辑,同样是当cur为空的时候循环结束,不断将cur指向pre的过程。 - -关键是初始化的地方,可能有的同学会不理解, 可以看到双指针法中初始化 cur = head,pre = NULL,在递归法中可以从如下代码看出初始化的逻辑也是一样的,只不过写法变了。 - -具体可以看代码(已经详细注释),**双指针法写出来之后,理解如下递归写法就不难了,代码逻辑都是一样的。** -```CPP -class Solution { -public: - ListNode* reverse(ListNode* pre,ListNode* cur){ - if(cur == NULL) return pre; - ListNode* temp = cur->next; - cur->next = pre; - // 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步 - // pre = cur; - // cur = temp; - return reverse(cur,temp); - } - ListNode* reverseList(ListNode* head) { - // 和双指针法初始化是一样的逻辑 - // ListNode* cur = head; - // ListNode* pre = NULL; - return reverse(NULL, head); - } - -}; -``` - -* 时间复杂度: O(n), 要递归处理链表的每个节点 -* 空间复杂度: O(n), 递归调用了 n 层栈空间 - -我们可以发现,上面的递归写法和双指针法实质上都是从前往后翻转指针指向,其实还有另外一种与双指针法不同思路的递归写法:从后往前翻转指针指向。 - -具体代码如下(带详细注释): - -```CPP -class Solution { -public: - ListNode* reverseList(ListNode* head) { - // 边缘条件判断 - if(head == NULL) return NULL; - if (head->next == NULL) return head; - - // 递归调用,翻转第二个节点开始往后的链表 - ListNode *last = reverseList(head->next); - // 翻转头节点与第二个节点的指向 - head->next->next = head; - // 此时的 head 节点为尾节点,next 需要指向 NULL - head->next = NULL; - return last; - } -}; -``` - -* 时间复杂度: O(n) -* 空间复杂度: O(n) - - -## 其他语言版本 - -### Java: - -```java -// 双指针 -class Solution { - public ListNode reverseList(ListNode head) { - ListNode prev = null; - ListNode cur = head; - ListNode temp = null; - while (cur != null) { - temp = cur.next;// 保存下一个节点 - cur.next = prev; - prev = cur; - cur = temp; - } - return prev; - } -} -``` - -```java -// 递归 -class Solution { - public ListNode reverseList(ListNode head) { - return reverse(null, head); - } - - private ListNode reverse(ListNode prev, ListNode cur) { - if (cur == null) { - return prev; - } - ListNode temp = null; - temp = cur.next;// 先保存下一个节点 - cur.next = prev;// 反转 - // 更新prev、cur位置 - // prev = cur; - // cur = temp; - return reverse(cur, temp); - } -} -``` - -```java -// 从后向前递归 -class Solution { - ListNode reverseList(ListNode head) { - // 边缘条件判断 - if(head == null) return null; - if (head.next == null) return head; - - // 递归调用,翻转第二个节点开始往后的链表 - ListNode last = reverseList(head.next); - // 翻转头节点与第二个节点的指向 - head.next.next = head; - // 此时的 head 节点为尾节点,next 需要指向 NULL - head.next = null; - return last; - } -} -``` - -### Python: - -```python -(版本一)双指针法 -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def reverseList(self, head: ListNode) -> ListNode: - cur = head - pre = None - while cur: - temp = cur.next # 保存一下 cur的下一个节点,因为接下来要改变cur->next - cur.next = pre #反转 - #更新pre、cur指针 - pre = cur - cur = temp - return pre -``` - -```python -(版本二)递归法 -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def reverseList(self, head: ListNode) -> ListNode: - return self.reverse(head, None) - def reverse(self, cur: ListNode, pre: ListNode) -> ListNode: - if cur == None: - return pre - temp = cur.next - cur.next = pre - return self.reverse(temp, cur) - -``` - - - -### Go: - -```go -//双指针 -func reverseList(head *ListNode) *ListNode { - var pre *ListNode - cur := head - for cur != nil { - next := cur.Next - cur.Next = pre - pre = cur - cur = next - } - return pre -} - -//递归 -func reverseList(head *ListNode) *ListNode { - return help(nil, head) -} - -func help(pre, head *ListNode)*ListNode{ - if head == nil { - return pre - } - next := head.Next - head.Next = pre - return help(head, next) -} - -``` -### JavaScript: - -```js -/** - * @param {ListNode} head - * @return {ListNode} - */ - -// 双指针: -var reverseList = function(head) { - if(!head || !head.next) return head; - let temp = null, pre = null, cur = head; - while(cur) { - temp = cur.next; - cur.next = pre; - pre = cur; - cur = temp; - } - // temp = cur = null; - return pre; -}; - -// 递归: -var reverse = function(pre, head) { - if(!head) return pre; - const temp = head.next; - head.next = pre; - pre = head - return reverse(pre, temp); -} - -var reverseList = function(head) { - return reverse(null, head); -}; - -// 递归2 -var reverse = function(head) { - if(!head || !head.next) return head; - // 从后往前翻 - const pre = reverse(head.next); - head.next = pre.next; - pre.next = head; - return head; -} - -var reverseList = function(head) { - let cur = head; - while(cur && cur.next) { - cur = cur.next; - } - reverse(head); - return cur; -}; -``` - -### TypeScript: - -```typescript -// 双指针法 -function reverseList(head: ListNode | null): ListNode | null { - let preNode: ListNode | null = null, - curNode: ListNode | null = head, - tempNode: ListNode | null; - while (curNode) { - tempNode = curNode.next; - curNode.next = preNode; - preNode = curNode; - curNode = tempNode; - } - return preNode; -}; - -// 递归(从前往后翻转) -function reverseList(head: ListNode | null): ListNode | null { - function recur(preNode: ListNode | null, curNode: ListNode | null): ListNode | null { - if (curNode === null) return preNode; - let tempNode: ListNode | null = curNode.next; - curNode.next = preNode; - preNode = curNode; - curNode = tempNode; - return recur(preNode, curNode); - } - return recur(null, head); -}; - -// 递归(从后往前翻转) -function reverseList(head: ListNode | null): ListNode | null { - if (head === null) return null; - let newHead: ListNode | null; - function recur(node: ListNode | null, preNode: ListNode | null): void { - if (node.next === null) { - newHead = node; - newHead.next = preNode; - } else { - recur(node.next, node); - node.next = preNode; - } - } - recur(head, null); - return newHead; -}; -``` - -### Ruby: - -```ruby -# 双指针 -# Definition for singly-linked list. -# class ListNode -# attr_accessor :val, :next -# def initialize(val = 0, _next = nil) -# @val = val -# @next = _next -# end -# end -def reverse_list(head) - # return nil if head.nil? # 循环判断条件亦能起到相同作用因此不必单独判断 - cur, per = head, nil - until cur.nil? - tem = cur.next - cur.next = per - per = cur - cur = tem - end - per -end - -# 递归 -# Definition for singly-linked list. -# class ListNode -# attr_accessor :val, :next -# def initialize(val = 0, _next = nil) -# @val = val -# @next = _next -# end -# end -def reverse_list(head) - reverse(nil, head) -end - -def reverse(pre, cur) - return pre if cur.nil? - tem = cur.next - cur.next = pre - reverse(cur, tem) # 通过递归实现双指针法中的更新操作 -end -``` - -### Kotlin: - -```Kotlin -fun reverseList(head: ListNode?): ListNode? { - var pre: ListNode? = null - var cur = head - while (cur != null) { - val temp = cur.next - cur.next = pre - pre = cur - cur = temp - } - return pre -} -``` -```kotlin -/** - * Example: - * var li = ListNode(5) - * var v = li.`val` - * Definition for singly-linked list. - * class ListNode(var `val`: Int) { - * var next: ListNode? = null - * } - */ -class Solution { - fun reverseList(head: ListNode?): ListNode? { - // temp用来存储临时的节点 - var temp: ListNode? - // cur用来遍历链表 - var cur: ListNode? = head - // pre用来作为链表反转的工具 - // pre是比pre前一位的节点 - var pre: ListNode? = null - while (cur != null) { - // 临时存储原本cur的下一个节点 - temp = cur.next - // 使cur下一节点地址为它之前的 - cur.next = pre - // 之后随着cur的遍历移动pre - pre = cur; - // 移动cur遍历链表各个节点 - cur = temp; - } - // 由于开头使用pre为null,所以cur等于链表本身长度+1, - // 此时pre在cur前一位,所以此时pre为头节点 - return pre; - } -} -``` - -### Swift: - -```swift -/// 双指针法 (迭代) -/// - Parameter head: 头结点 -/// - Returns: 翻转后的链表头结点 -func reverseList(_ head: ListNode?) -> ListNode? { - if head == nil || head?.next == nil { - return head - } - var pre: ListNode? = nil - var cur: ListNode? = head - var temp: ListNode? = nil - while cur != nil { - temp = cur?.next - cur?.next = pre - pre = cur - cur = temp - } - return pre -} - -/// 递归 -/// - Parameter head: 头结点 -/// - Returns: 翻转后的链表头结点 -func reverseList2(_ head: ListNode?) -> ListNode? { - return reverse(pre: nil, cur: head) -} -func reverse(pre: ListNode?, cur: ListNode?) -> ListNode? { - if cur == nil { - return pre - } - let temp: ListNode? = cur?.next - cur?.next = pre - return reverse(pre: cur, cur: temp) -} -``` - -### C: -双指针法: - -```c -struct ListNode* reverseList(struct ListNode* head){ - //保存cur的下一个结点 - struct ListNode* temp; - //pre指针指向前一个当前结点的前一个结点 - struct ListNode* pre = NULL; - //用head代替cur,也可以再定义一个cur结点指向head。 - while(head) { - //保存下一个结点的位置 - temp = head->next; - //翻转操作 - head->next = pre; - //更新结点 - pre = head; - head = temp; - } - return pre; -} -``` - -递归法: -```c -struct ListNode* reverse(struct ListNode* pre, struct ListNode* cur) { - if(!cur) - return pre; - struct ListNode* temp = cur->next; - cur->next = pre; - //将cur作为pre传入下一层 - //将temp作为cur传入下一层,改变其指针指向当前cur - return reverse(cur, temp); -} - -struct ListNode* reverseList(struct ListNode* head){ - return reverse(NULL, head); -} -``` - - - -### PHP: - -```php -// 双指针法: -function reverseList($head) { - $cur = $head; - $pre = NULL; - while($cur){ - $temp = $cur->next; - $cur->next = $pre; - $pre = $cur; - $cur = $temp; - } - return $pre; - } -``` - -### Scala: -双指针法: - -```scala -object Solution { - def reverseList(head: ListNode): ListNode = { - var pre: ListNode = null - var cur = head - while (cur != null) { - var tmp = cur.next - cur.next = pre - pre = cur - cur = tmp - } - pre - } -} -``` -递归法: -```scala -object Solution { - def reverseList(head: ListNode): ListNode = { - reverse(null, head) - } - - def reverse(pre: ListNode, cur: ListNode): ListNode = { - if (cur == null) { - return pre // 如果当前cur为空,则返回pre - } - val tmp: ListNode = cur.next - cur.next = pre - reverse(cur, tmp) // 此时cur成为前一个节点,tmp是当前节点 - } - -} -``` - -### Rust: -双指针法: - -```rust -impl Solution { - pub fn reverse_list(head: Option>) -> Option> { - let mut cur = head; - let mut pre = None; - while let Some(mut node) = cur.take() { - cur = node.next; - node.next = pre; - pre = Some(node); - } - pre - } -} -``` - -递归法: - -```rust -impl Solution { - pub fn reverse_list(head: Option>) -> Option> { - fn rev( - mut head: Option>, - mut pre: Option>, - ) -> Option> { - if let Some(mut node) = head.take() { - let cur = node.next; - node.next = pre; - pre = Some(node); - return rev(cur, pre); - } - pre - } - rev(head, None) - } -} -``` -### C#: -三指针法, 感觉会更直观: - -```cs -public LinkNumbers Reverse() -{ - ///用三指针,写的过程中能够弥补二指针在翻转过程中的想象 - LinkNumbers pre = null; - var move = root; - var next = root; - - while (next != null) - { - next = next.linknext; - move.linknext = pre; - pre = move; - move = next; - } - root = pre; - return root; -} - -///LinkNumbers的定义 -public class LinkNumbers -{ - /// - /// 链表值 - /// - public int value { get; set; } - - /// - /// 链表指针 - /// - public LinkNumbers linknext { get; set; } -} -``` - -## 其他解法 - -### 使用虚拟头结点解决链表反转 - -> 使用虚拟头结点,通过头插法实现链表的反转(不需要栈) - -```java -// 迭代方法:增加虚头结点,使用头插法实现链表翻转 -public static ListNode reverseList1(ListNode head) { - // 创建虚头结点 - ListNode dumpyHead = new ListNode(-1); - dumpyHead.next = null; - // 遍历所有节点 - ListNode cur = head; - while(cur != null){ - ListNode temp = cur.next; - // 头插法 - cur.next = dumpyHead.next; - dumpyHead.next = cur; - cur = temp; - } - return dumpyHead.next; -} -``` - - - -### 使用栈解决反转链表的问题 - -* 首先将所有的结点入栈 -* 然后创建一个虚拟虚拟头结点,让cur指向虚拟头结点。然后开始循环出栈,每出来一个元素,就把它加入到以虚拟头结点为头结点的链表当中,最后返回即可。 - -```java -public ListNode reverseList(ListNode head) { - // 如果链表为空,则返回空 - if (head == null) return null; - // 如果链表中只有只有一个元素,则直接返回 - if (head.next == null) return head; - // 创建栈 每一个结点都入栈 - Stack stack = new Stack<>(); - ListNode cur = head; - while (cur != null) { - stack.push(cur); - cur = cur.next; - } - // 创建一个虚拟头结点 - ListNode pHead = new ListNode(0); - cur = pHead; - while (!stack.isEmpty()) { - ListNode node = stack.pop(); - cur.next = node; - cur = cur.next; - } - // 最后一个元素的next要赋值为空 - cur.next = null; - return pHead.next; -} -``` - -> 采用这种方法需要注意一点。就是当整个出栈循环结束以后,cur正好指向原来链表的第一个结点,而此时结点1中的next指向的是结点2,因此最后还需要`cur.next = null` -![image-20230117195418626](https://raw.githubusercontent.com/liyuxuan7762/MyImageOSS/master/md_images/image-20230117195418626.png) - -

- - - From a64e11b09ad66f4a1ea22cdc3603e5cde85d88ef Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Tue, 18 Jul 2023 15:13:42 +0800 Subject: [PATCH 23/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20019.=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=AC?= =?UTF-8?q?n=E4=B8=AA=E8=8A=82=E7=82=B9=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0019.删除链表的倒数第N个节点.md | 39 ++++++++++++------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index 84eac96b..1c95ad5b 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -7,7 +7,7 @@ -## 19.删除链表的倒数第N个节点 +# 19.删除链表的倒数第N个节点 [力扣题目链接](https://leetcode.cn/problems/remove-nth-node-from-end-of-list/) @@ -31,11 +31,13 @@ 输入:head = [1,2], n = 1 输出:[1] +## 算法公开课 + +**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html)::[链表遍历学清楚! | LeetCode:19.删除链表倒数第N个节点](https://www.bilibili.com/video/BV1vW4y1U7Gf),相信结合视频再看本篇题解,更有助于大家对链表的理解。** + ## 思路 -《代码随想录》算法公开课:[链表遍历学清楚! | LeetCode:19.删除链表倒数第N个节点](https://www.bilibili.com/video/BV1vW4y1U7Gf),相信结合视频在看本篇题解,更有助于大家对链表的理解。 - 双指针的经典应用,如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾。删掉slow所指向的节点就可以了。 @@ -93,7 +95,7 @@ public: ## 其他语言版本 -java: +### Java: ```java public ListNode removeNthFromEnd(ListNode head, int n){ @@ -120,7 +122,8 @@ public ListNode removeNthFromEnd(ListNode head, int n){ } ``` -Python: +### Python: + ```python # Definition for singly-linked list. # class ListNode: @@ -151,7 +154,8 @@ class Solution: return dummy_head.next ``` -Go: +### Go: + ```Go /** * Definition for singly-linked list. @@ -178,7 +182,7 @@ func removeNthFromEnd(head *ListNode, n int) *ListNode { } ``` -JavaScript: +### JavaScript: ```js /** @@ -198,7 +202,7 @@ var removeNthFromEnd = function(head, n) { return ret.next; }; ``` -TypeScript: +### TypeScript: 版本一(快慢指针法): @@ -263,7 +267,7 @@ function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { }; ``` -Kotlin: +### Kotlin: ```Kotlin fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { @@ -284,7 +288,8 @@ fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { } ``` -Swift: +### Swift: + ```swift func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? { if head == nil { @@ -309,8 +314,8 @@ func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? { } ``` +### PHP: -PHP: ```php function removeNthFromEnd($head, $n) { // 设置虚拟头节点 @@ -332,7 +337,8 @@ function removeNthFromEnd($head, $n) { } ``` -Scala: +### Scala: + ```scala object Solution { def removeNthFromEnd(head: ListNode, n: Int): ListNode = { @@ -356,7 +362,8 @@ object Solution { } ``` -Rust: +### Rust: + ```rust impl Solution { pub fn remove_nth_from_end(head: Option>, mut n: i32) -> Option> { @@ -377,7 +384,8 @@ impl Solution { } } ``` -C语言 +### C: + ```c /**c语言单链表的定义 * Definition for singly-linked list. @@ -412,7 +420,8 @@ struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { ``` -C#: +### C#: + ```csharp public class Solution { public ListNode RemoveNthFromEnd(ListNode head, int n) { From 8eb214c06025e359d9c4a40d87d4e3075f5d8bdf Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Tue, 18 Jul 2023 15:23:24 +0800 Subject: [PATCH 24/26] =?UTF-8?q?=E9=9D=A2=E8=AF=95=E9=A2=98=2002.07.?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4=20=E6=8E=92=E7=89=88?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 75e03116..833eadca 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -34,6 +34,7 @@ ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211219221812.png)![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211219221812.png) + ## 思路 @@ -101,7 +102,7 @@ public: ## 其他语言版本 -Java: +### Java: ```Java public class Solution { @@ -150,8 +151,7 @@ public class Solution { } ``` - -Python: +### Python: ```python @@ -280,7 +280,7 @@ class Solution: return pointerA ``` -Go: +### Go: ```go func getIntersectionNode(headA, headB *ListNode) *ListNode { @@ -341,7 +341,7 @@ func getIntersectionNode(headA, headB *ListNode) *ListNode { } ``` -JavaScript: +### JavaScript: ```js var getListLen = function(head) { @@ -376,7 +376,7 @@ var getIntersectionNode = function(headA, headB) { }; ``` -TypeScript: +### TypeScript: ```typescript function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null { @@ -413,7 +413,7 @@ function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): Li }; ``` -C: +### C: ```c ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { @@ -452,7 +452,7 @@ ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { } ``` -Scala: +### Scala: ```scala object Solution { @@ -508,3 +508,4 @@ object Solution { + From 17d56ed722d41a8d463de2de71c72345a88a2df5 Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Tue, 18 Jul 2023 15:30:49 +0800 Subject: [PATCH 25/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200142.=E7=8E=AF?= =?UTF-8?q?=E5=BD=A2=E9=93=BE=E8=A1=A8II=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0141.环形链表.md | 11 ++++++----- problems/0142.环形链表II.md | 30 +++++++++++++++--------------- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/problems/0141.环形链表.md b/problems/0141.环形链表.md index 7d7121a0..b1f42ba9 100644 --- a/problems/0141.环形链表.md +++ b/problems/0141.环形链表.md @@ -70,7 +70,7 @@ public: ## 其他语言版本 -### Java +### Java: ```java public class Solution { @@ -90,7 +90,7 @@ public class Solution { } ``` -### Python +### Python: ```python class Solution: @@ -105,7 +105,7 @@ class Solution: return False ``` -### Go +### Go: ```go func hasCycle(head *ListNode) bool { @@ -125,7 +125,7 @@ func hasCycle(head *ListNode) bool { } ``` -### JavaScript +### JavaScript: ```js var hasCycle = function(head) { @@ -141,7 +141,7 @@ var hasCycle = function(head) { }; ``` -### TypeScript +### TypeScript: ```typescript function hasCycle(head: ListNode | null): boolean { @@ -163,3 +163,4 @@ function hasCycle(head: ListNode | null): boolean { + diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index f87d2cd9..d20101a7 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -11,7 +11,7 @@ > 找到有没有环已经很不容易了,还要让我找到环的入口? -## 142.环形链表II +# 142.环形链表II [力扣题目链接](https://leetcode.cn/problems/linked-list-cycle-ii/) @@ -24,9 +24,11 @@ ![循环链表](https://code-thinking-1253855093.file.myqcloud.com/pics/20200816110112704.png) -## 思路 +## 算法公开课 -《代码随想录》算法公开课:[把环形链表讲清楚!| LeetCode:142.环形链表II](https://www.bilibili.com/video/BV1if4y1d7ob),相信结合视频在看本篇题解,更有助于大家对链表的理解。 +**[《代码随想录》算法视频公开课](https://programmercarl.com/other/gongkaike.html):[把环形链表讲清楚!| LeetCode:142.环形链表II](https://www.bilibili.com/video/BV1if4y1d7ob),相信结合视频在看本篇题解,更有助于大家对链表的理解。** + +## 思路 这道题目,不仅考察对链表的操作,而且还需要一些数学运算。 @@ -148,7 +150,7 @@ public: * 时间复杂度: O(n),快慢指针相遇前,指针走的次数小于链表长度,快慢指针相遇后,两个index指针走的次数也小于链表长度,总体为走的次数小于 2n * 空间复杂度: O(1) -## 补充 +### 补充 在推理过程中,大家可能有一个疑问就是:**为什么第一次在环中相遇,slow的 步数 是 x+y 而不是 x + 若干环的长度 + y 呢?** @@ -190,8 +192,7 @@ public: ## 其他语言版本 - -Java: +### Java: ```java public class Solution { @@ -217,8 +218,7 @@ public class Solution { } ``` - -Python: +### Python: ```python (版本一)快慢指针法 @@ -270,7 +270,7 @@ class Solution: return None ``` -Go: +### Go: ```go func detectCycle(head *ListNode) *ListNode { @@ -290,7 +290,7 @@ func detectCycle(head *ListNode) *ListNode { } ``` -javaScript +### JavaScript ```js // 两种循环实现方式 @@ -334,7 +334,7 @@ var detectCycle = function(head) { }; ``` -TypeScript: +### TypeScript: ```typescript function detectCycle(head: ListNode | null): ListNode | null { @@ -356,7 +356,7 @@ function detectCycle(head: ListNode | null): ListNode | null { }; ``` -Swift: +### Swift: ```swift class Solution { @@ -391,7 +391,7 @@ extension ListNode: Equatable { } ``` -C: +### C: ```c ListNode *detectCycle(ListNode *head) { @@ -410,7 +410,7 @@ ListNode *detectCycle(ListNode *head) { } ``` -Scala: +### Scala: ```scala object Solution { @@ -437,7 +437,7 @@ object Solution { } ``` -C#: +### C#: ```CSharp public class Solution { From 28b58782375755eda70381aaab630e52b50992c8 Mon Sep 17 00:00:00 2001 From: jinbudaily <18336218010@163.com> Date: Tue, 18 Jul 2023 15:33:00 +0800 Subject: [PATCH 26/26] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E6=80=BB=E7=BB=93=E7=AF=87=20=E6=8E=92=E7=89=88=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/链表总结篇.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/problems/链表总结篇.md b/problems/链表总结篇.md index cfbafc45..dacd4dee 100644 --- a/problems/链表总结篇.md +++ b/problems/链表总结篇.md @@ -3,7 +3,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- +# 链表总结篇 ## 链表的理论基础 @@ -68,7 +68,7 @@ [链表:链表相交](https://programmercarl.com/面试题02.07.链表相交.html)使用双指针来找到两个链表的交点(引用完全相同,即:内存地址完全相同的交点) -## 环形链表 +### 环形链表 在[链表:环找到了,那入口呢?](https://programmercarl.com/0142.环形链表II.html)中,讲解了在链表如何找环,以及如何找环的入口位置。 @@ -100,3 +100,4 @@ +