diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index b1987b87..614f6051 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -30,17 +30,17 @@ * 输出:"a" -# 思路 +## 思路 本题和[647.回文子串](https://programmercarl.com/0647.回文子串.html) 差不多是一样的,但647.回文子串更基本一点,建议可以先做647.回文子串 -## 暴力解法 +### 暴力解法 两层for循环,遍历区间起始位置和终止位置,然后判断这个区间是不是回文。 时间复杂度:O(n^3) -## 动态规划 +### 动态规划 动规五部曲: @@ -208,7 +208,7 @@ public: * 时间复杂度:O(n^2) * 空间复杂度:O(n^2) -## 双指针 +### 双指针 动态规划的空间复杂度是偏高的,我们再看一下双指针法。 @@ -258,9 +258,9 @@ public: -# 其他语言版本 +## 其他语言版本 -Java: +### Java: ```java // 双指针 动态规划 @@ -327,7 +327,7 @@ class Solution { } ``` -Python: +### Python: ```python class Solution: @@ -377,7 +377,7 @@ class Solution: return s[start:end] ``` -Go: +### Go: ```go func longestPalindrome(s string) string { @@ -411,7 +411,7 @@ func longestPalindrome(s string) string { ``` -JavaScript: +### JavaScript: ```js //动态规划解法 @@ -527,7 +527,7 @@ var longestPalindrome = function(s) { }; ``` -C: +### C: 动态规划: ```c @@ -615,7 +615,7 @@ char * longestPalindrome(char * s){ } ``` -C#: +### C#: 動態規則: ```c# @@ -681,3 +681,4 @@ public class Solution { + diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index 34aa1086..3cfb673a 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -34,7 +34,7 @@ * 输出:[1] -# 思路 +## 思路 一些同学可能手动写排列的顺序,都没有写对,那么写程序的话思路一定是有问题的了,我这里以1234为例子,把全排列都列出来。可以参考一下规律所在: @@ -92,9 +92,9 @@ public: }; ``` -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java class Solution { @@ -159,7 +159,7 @@ class Solution { } ``` -## Python +### Python >直接使用sorted()会开辟新的空间并返回一个新的list,故补充一个原地反转函数 ```python class Solution: @@ -191,7 +191,7 @@ class Solution: """ ``` -## Go +### Go ```go //卡尔的解法 @@ -216,7 +216,7 @@ func reverse(a []int,begin,end int){ } ``` -## JavaScript +### JavaScript ```js //卡尔的解法(吐槽一下JavaScript的sort和其他语言的不太一样,只想到了拷贝数组去排序再替换原数组来实现nums的[i + 1, nums.length)升序排序) @@ -272,3 +272,4 @@ var nextPermutation = function(nums) { + diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index 833a7613..1f1a543b 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -29,7 +29,7 @@ * 输出:9 -# 思路 +## 思路 接雨水问题在面试中还是常见题目的,有必要好好讲一讲。 @@ -39,7 +39,7 @@ * 动态规划 * 单调栈 -## 暴力解法 +### 暴力解法 本题暴力解法也是也是使用双指针。 @@ -137,7 +137,7 @@ public: 力扣后面修改了后台测试数据,所以以上暴力解法超时了。 -## 双指针优化 +### 双指针优化 在暴力解法中,我们可以看到只要记录左边柱子的最高高度 和 右边柱子的最高高度,就可以计算当前位置的雨水面积,这就是通过列来计算。 @@ -184,7 +184,7 @@ public: }; ``` -## 单调栈解法 +### 单调栈解法 关于单调栈的理论基础,单调栈适合解决什么问题,单调栈的工作过程,大家可以先看这题讲解 [739. 每日温度](https://programmercarl.com/0739.每日温度.html)。 @@ -194,7 +194,7 @@ public: 而接雨水这道题目,我们正需要寻找一个元素,右边最大元素以及左边最大元素,来计算雨水面积。 -### 准备工作 +#### 准备工作 那么本题使用单调栈有如下几个问题: @@ -248,7 +248,7 @@ stack st; // 存着下标,计算的时候用下标对应的柱子高度 明确了如上几点,我们再来看处理逻辑。 -### 单调栈处理逻辑 +#### 单调栈处理逻辑 以下操作过程其实和 [739. 每日温度](https://programmercarl.com/0739.每日温度.html) 也是一样的,建议先做 [739. 每日温度](https://programmercarl.com/0739.每日温度.html)。 @@ -596,7 +596,7 @@ class Solution: ``` -### Go +### Go: ```go func trap(height []int) int { @@ -802,7 +802,7 @@ var trap = function(height) { }; ``` -### TypeScript +### TypeScript: 暴力解法: @@ -925,6 +925,55 @@ int trap(int* height, int heightSize) { * 时间复杂度 O(n) * 空间复杂度 O(1) +### Rust: + +双指针 + +```rust +impl Solution { + pub fn trap(height: Vec) -> i32 { + let n = height.len(); + let mut max_left = vec![0; height.len()]; + let mut max_right = vec![0; height.len()]; + max_left.iter_mut().zip(max_right.iter_mut().rev()).enumerate().fold((0, 0), |(lm, rm), (idx, (x, y))| { + let lmax = lm.max(height[idx]); + let rmax = rm.max(height[n - 1 - idx]); + *x = lmax; *y = rmax; + (lmax, rmax) + }); + height.iter().enumerate().fold(0, |acc, (idx, x)| { + let h = max_left[idx].min(max_right[idx]); + if h > 0 { h - x + acc } else { acc } + }) + } +} +``` + +单调栈 + +```rust +impl Solution { + pub fn trap(height: Vec) -> i32 { + let mut stack = vec![]; + let mut ans = 0; + for (right_pos, &right_h) in height.iter().enumerate() { + while !stack.is_empty() && height[*stack.last().unwrap()] <= right_h { + let mid_pos = stack.pop().unwrap(); + if !stack.is_empty() { + let left_pos = *stack.last().unwrap(); + let left_h = height[left_pos]; + let top = std::cmp::min(left_h, right_h); + if top > height[mid_pos] { + ans += (top - height[mid_pos]) * (right_pos - left_pos - 1) as i32; + } + } + } + stack.push(right_pos); + } + ans + } +} +``` Rust @@ -980,3 +1029,4 @@ impl Solution { + diff --git a/problems/0084.柱状图中最大的矩形.md b/problems/0084.柱状图中最大的矩形.md index bc82a860..9b76229a 100644 --- a/problems/0084.柱状图中最大的矩形.md +++ b/problems/0084.柱状图中最大的矩形.md @@ -20,7 +20,7 @@ * 1 <= heights.length <=10^5 * 0 <= heights[i] <= 10^4 -# 思路 +## 思路 本题和[42. 接雨水](https://programmercarl.com/0042.接雨水.html),是遥相呼应的两道题目,建议都要仔细做一做,原理上有很多相同的地方,但细节上又有差异,更可以加深对单调栈的理解! @@ -28,7 +28,7 @@ 我们先来看一下暴力解法的解法: -## 暴力解法 +### 暴力解法 ```CPP class Solution { @@ -55,7 +55,7 @@ public: 如上代码并不能通过leetcode,超时了,因为时间复杂度是$O(n^2)$。 -## 双指针解法 +### 双指针解法 本题双指针的写法整体思路和[42. 接雨水](https://programmercarl.com/0042.接雨水.html)是一致的,但要比[42. 接雨水](https://programmercarl.com/0042.接雨水.html)难一些。 @@ -98,7 +98,7 @@ public: }; ``` -## 单调栈 +### 单调栈 本地单调栈的解法和接雨水的题目是遥相呼应的。 @@ -169,7 +169,7 @@ public: } }; -``` +``` 细心的录友会发现,我在 height数组上后,都加了一个元素0, 为什么这么做呢? @@ -229,7 +229,7 @@ public: ## 其他语言版本 -Java: +### Java: 暴力解法: ```java @@ -335,7 +335,7 @@ class Solution { } ``` -Python3: +### Python3: ```python @@ -468,7 +468,7 @@ class Solution: ``` -Go: +### Go: > 单调栈 @@ -506,7 +506,8 @@ func largestRectangleArea(heights []int) int { ``` -JavaScript: +### JavaScript: + ```javascript //双指针 js中运行速度最快 var largestRectangleArea = function(heights) { @@ -581,7 +582,7 @@ var largestRectangleArea = function(heights) { return maxArea; }; ``` -TypeScript: +### TypeScript: > 暴力法(会超时): @@ -669,6 +670,60 @@ function largestRectangleArea(heights: number[]): number { }; ``` +### Rust: + +双指针预处理 +```rust + +impl Solution { + pub fn largest_rectangle_area(v: Vec) -> i32 { + let n = v.len(); + let mut left_smaller_idx = vec![-1; n]; + let mut right_smaller_idx = vec![n as i32; n]; + for i in 1..n { + let mut mid = i as i32 - 1; + while mid >= 0 && v[mid as usize] >= v[i] { + mid = left_smaller_idx[mid as usize]; + } + left_smaller_idx[i] = mid; + } + for i in (0..n-1).rev() { + let mut mid = i + 1; + while mid < n && v[mid] >= v[i] { + mid = right_smaller_idx[mid] as usize; + } + right_smaller_idx[i] = mid as i32; + } + let mut res = 0; + for (idx, &e) in v.iter().enumerate() { + res = res.max((right_smaller_idx[idx] - left_smaller_idx[idx] - 1) * e); + } + dbg!(res) + } +} +``` + +单调栈 +```rust +impl Solution { + pub fn largest_rectangle_area1(mut v: Vec) -> i32 { + v.insert(0, 0); // 便于使第一个元素能够有左侧<=它的值 + v.push(0); // 便于在结束处理最后一个元素后清空残留在栈中的值 + let mut res = 0; + let mut stack = vec![]; // 递增的栈 + for (idx, &e) in v.iter().enumerate() { + while !stack.is_empty() && v[*stack.last().unwrap()] > e { + let pos = stack.pop().unwrap(); + let prev_pos = *stack.last().unwrap(); + let s = (idx - prev_pos - 1) as i32 * v[pos]; + res = res.max(s); + } + stack.push(idx); + } + res + } +} +``` Rust @@ -730,3 +785,4 @@ impl Solution { + diff --git a/problems/0100.相同的树.md b/problems/0100.相同的树.md index 96acacf6..56a6c884 100644 --- a/problems/0100.相同的树.md +++ b/problems/0100.相同的树.md @@ -19,7 +19,7 @@ ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210726173011.png) -# 思路 +## 思路 在[101.对称二叉树](https://programmercarl.com/0101.对称二叉树.html)中,我们讲到对于二叉树是否对称,要比较的是根节点的左子树与右子树是不是相互翻转的,理解这一点就知道了**其实我们要比较的是两个树(这两个树是根节点的左右子树)**,所以在递归遍历的过程中,也是要同时遍历两棵树。 @@ -115,7 +115,7 @@ public: 当然我可以把如上代码整理如下: -## 递归 +### 递归 ```CPP class Solution { @@ -134,7 +134,7 @@ public: }; ``` -## 迭代法 +### 迭代法 ```CPP class Solution { @@ -166,9 +166,9 @@ public: }; ``` -# 其他语言版本 +## 其他语言版本 -Java: +### Java: ```java // 递归法 @@ -205,7 +205,8 @@ class Solution { } } ``` -Python: +### Python: + ```python # 递归法 class Solution: @@ -236,7 +237,8 @@ class Solution: que.append(rightNode.right) return True ``` -Go: +### Go: + > 递归法 ```go func isSameTree(p *TreeNode, q *TreeNode) bool { @@ -258,7 +260,7 @@ func isSameTree(p *TreeNode, q *TreeNode) bool { } ``` -JavaScript: +### JavaScript: > 递归法 @@ -296,7 +298,7 @@ var isSameTree = (p, q) => { }; ``` -TypeScript: +### TypeScript: > 递归法-先序遍历 @@ -341,3 +343,4 @@ function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { + diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index 31bb6822..003ef75a 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -30,7 +30,7 @@ struct Node { ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210727143202.png) -# 思路 +## 思路 注意题目提示内容,: * 你只能使用常量级额外空间。 @@ -38,7 +38,7 @@ struct Node { 基本上就是要求使用递归了,迭代的方式一定会用到栈或者队列。 -## 递归 +### 递归 一想用递归怎么做呢,虽然层序遍历是最直观的,但是递归的方式确实不好想。 @@ -83,7 +83,7 @@ public: }; ``` -## 迭代(层序遍历) +### 迭代(层序遍历) 本题使用层序遍历是最为直观的,如果对层序遍历不了解,看这篇:[二叉树:层序遍历登场!](https://programmercarl.com/0102.二叉树的层序遍历.html)。 @@ -114,9 +114,9 @@ public: }; ``` -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java // 递归法 @@ -169,7 +169,7 @@ class Solution { } ``` -## Python +### Python ```python # 递归法 @@ -210,7 +210,7 @@ class Solution: nodePre.next = None # 本层最后一个节点指向None return root ``` -## Go +### Go ```go // 迭代法 func connect(root *Node) *Node { @@ -259,7 +259,7 @@ func connect(root *Node) *Node { } ``` -## JavaScript +### JavaScript ```js const connect = root => { @@ -287,7 +287,7 @@ const connect = root => { }; ``` -## TypeScript +### TypeScript (注:命名空间‘Node’与typescript中内置类型冲突,这里改成了‘NodePro’) @@ -365,3 +365,4 @@ function connect(root: NodePro | null): NodePro | null { + diff --git a/problems/0127.单词接龙.md b/problems/0127.单词接龙.md index 20ad5182..97bc66d0 100644 --- a/problems/0127.单词接龙.md +++ b/problems/0127.单词接龙.md @@ -29,7 +29,7 @@ * 解释:endWord "cog" 不在字典中,所以无法进行转换。 -# 思路 +## 思路 以示例1为例,从这个图中可以看出 hit 到 cog的路线,不止一条,有三条,一条是最短的长度为5,两条长度为6。 @@ -97,9 +97,9 @@ public: 当然本题也可以用双向BFS,就是从头尾两端进行搜索,大家感兴趣,可以自己去实现,这里就不再做详细讲解了。 -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java public int ladderLength(String beginWord, String endWord, List wordList) { @@ -196,7 +196,7 @@ class Solution { } ``` -## Python +### Python ``` class Solution: @@ -221,7 +221,7 @@ class Solution: queue.append(newWord) return 0 ``` -## Go +### Go ```go func ladderLength(beginWord string, endWord string, wordList []string) int { wordMap, que, depth := getWordMap(wordList, beginWord), []string{beginWord}, 0 @@ -274,7 +274,7 @@ func getCandidates(word string) []string { } ``` -## JavaScript +### JavaScript ```javascript var ladderLength = function(beginWord, endWord, wordList) { // 将wordList转成Set,提高查询速度 @@ -310,7 +310,7 @@ var ladderLength = function(beginWord, endWord, wordList) { }; ``` -## TypeScript +### TypeScript ```typescript function ladderLength( beginWord: string, @@ -364,4 +364,3 @@ function diffonechar(word1: string, word2: string): boolean { - diff --git a/problems/0129.求根到叶子节点数字之和.md b/problems/0129.求根到叶子节点数字之和.md index 445e108a..ebb36071 100644 --- a/problems/0129.求根到叶子节点数字之和.md +++ b/problems/0129.求根到叶子节点数字之和.md @@ -10,7 +10,7 @@ [力扣题目链接](https://leetcode.cn/problems/sum-root-to-leaf-numbers/) -# 思路 +## 思路 本题和[113.路径总和II](https://programmercarl.com/0112.路径总和.html#_113-路径总和ii)是类似的思路,做完这道题,可以顺便把[113.路径总和II](https://programmercarl.com/0112.路径总和.html#_113-路径总和ii) 和 [112.路径总和](https://programmercarl.com/0112.路径总和.html#_112-路径总和) 做了。 @@ -24,7 +24,7 @@ 那么先按递归三部曲来分析: -## 递归三部曲 +### 递归三部曲 如果对递归三部曲不了解的话,可以看这里:[二叉树:前中后递归详解](https://programmercarl.com/二叉树的递归遍历.html) @@ -116,7 +116,7 @@ path.pop_back(); // 回溯 ``` **把回溯放在花括号外面了,世界上最遥远的距离,是你在花括号里,而我在花括号外!** 这就不对了。 -## 整体C++代码 +整体C++代码 关键逻辑分析完了,整体C++代码如下: @@ -162,16 +162,16 @@ public: }; ``` -# 总结 +## 总结 过于简洁的代码,很容易让初学者忽视了本题中回溯的精髓,甚至作者本身都没有想清楚自己用了回溯。 **我这里提供的代码把整个回溯过程充分体现出来,希望可以帮助大家看的明明白白!** -# 其他语言版本 +## 其他语言版本 -Java: +### Java: ```java class Solution { @@ -219,7 +219,8 @@ class Solution { } ``` -Python: +### Python: + ```python class Solution: def sumNumbers(self, root: TreeNode) -> int: @@ -246,7 +247,7 @@ class Solution: backtrace(root) return res ``` -Go: +### Go: ```go func sumNumbers(root *TreeNode) int { @@ -271,7 +272,8 @@ func dfs(root *TreeNode, tmpSum int, sum *int) { -JavaScript: +### JavaScript: + ```javascript var sumNumbers = function(root) { const listToInt = path => { @@ -315,7 +317,7 @@ var sumNumbers = function(root) { }; ``` -TypeScript: +### TypeScript: ```typescript function sumNumbers(root: TreeNode | null): number { @@ -351,7 +353,7 @@ function sumNumbers(root: TreeNode | null): number { }; ``` -C: +### C: ```c //sum记录总和 @@ -384,3 +386,4 @@ int sumNumbers(struct TreeNode* root){ + diff --git a/problems/0132.分割回文串II.md b/problems/0132.分割回文串II.md index 9b164dfb..eb91a189 100644 --- a/problems/0132.分割回文串II.md +++ b/problems/0132.分割回文串II.md @@ -34,7 +34,7 @@ * 1 <= s.length <= 2000 * s 仅由小写英文字母组成 -# 思路 +## 思路 我们在讲解回溯法系列的时候,讲过了这道题目[回溯算法:131.分割回文串](https://programmercarl.com/0131.分割回文串.html)。 @@ -201,9 +201,9 @@ public: ``` -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java class Solution { @@ -257,7 +257,7 @@ class Solution { } ``` -## Python +### Python ```python class Solution: @@ -286,7 +286,7 @@ class Solution: return dp[-1] ``` -## Go +### Go ```go func minCut(s string) int { @@ -330,7 +330,7 @@ func min(i, j int) int { } ``` -## JavaScript +### JavaScript ```js var minCut = function(s) { @@ -376,3 +376,4 @@ var minCut = function(s) { + diff --git a/problems/0189.旋转数组.md b/problems/0189.旋转数组.md index 35819694..d60612e9 100644 --- a/problems/0189.旋转数组.md +++ b/problems/0189.旋转数组.md @@ -33,7 +33,7 @@ 向右旋转 2 步: [3,99,-1,-100]。 -# 思路 +## 思路 这道题目在字符串里其实很常见,我把字符串反转相关的题目列一下: @@ -83,9 +83,9 @@ public: ``` -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java class Solution { @@ -106,7 +106,7 @@ class Solution { } ``` -## Python +### Python 方法一:局部翻转 + 整体翻转 ```python @@ -139,7 +139,7 @@ class Solution: # 备注:这个方法会导致空间复杂度变成 O(n) 因为我们要创建一个 copy 数组。但是不失为一种思路。 ``` -## Go +### Go ```go func rotate(nums []int, k int) { @@ -157,7 +157,7 @@ func reverse(nums []int){ } ``` -## JavaScript +### JavaScript ```js var rotate = function (nums, k) { @@ -178,7 +178,7 @@ var rotate = function (nums, k) { }; ``` -## TypeScript +### TypeScript ```typescript function rotate(nums: number[], k: number): void { @@ -205,3 +205,4 @@ function reverseByRange(nums: number[], left: number, right: number): void { + diff --git a/problems/0205.同构字符串.md b/problems/0205.同构字符串.md index a507638c..e07ab746 100644 --- a/problems/0205.同构字符串.md +++ b/problems/0205.同构字符串.md @@ -29,7 +29,7 @@ 提示:可以假设 s 和 t 长度相同。 -# 思路 +## 思路 字符串没有说都是小写字母之类的,所以用数组不合适了,用map来做映射。 @@ -61,9 +61,9 @@ public: ``` -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java class Solution { @@ -87,7 +87,7 @@ class Solution { } ``` -## Python +### Python ```python class Solution: @@ -110,7 +110,7 @@ class Solution: return True ``` -## Go +### Go ```go func isIsomorphic(s string, t string) bool { @@ -132,7 +132,7 @@ func isIsomorphic(s string, t string) bool { } ``` -## JavaScript +### JavaScript ```js var isIsomorphic = function(s, t) { @@ -156,7 +156,7 @@ var isIsomorphic = function(s, t) { }; ``` -## TypeScript +### TypeScript ```typescript function isIsomorphic(s: string, t: string): boolean { @@ -183,3 +183,4 @@ function isIsomorphic(s: string, t: string): boolean { + diff --git a/problems/0234.回文链表.md b/problems/0234.回文链表.md index 18b397e3..fef942fc 100644 --- a/problems/0234.回文链表.md +++ b/problems/0234.回文链表.md @@ -432,3 +432,4 @@ function reverseList(head: ListNode | null): ListNode | null { + diff --git a/problems/0283.移动零.md b/problems/0283.移动零.md index 22d6428c..ee3f4291 100644 --- a/problems/0283.移动零.md +++ b/problems/0283.移动零.md @@ -3,10 +3,7 @@

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

- -# 动态规划:一样的套路,再求一次完全平方数 - -# 283. 移动零 +# 283. 移动零:动态规划:一样的套路,再求一次完全平方数 [力扣题目链接](https://leetcode.cn/problems/move-zeroes/) @@ -22,7 +19,7 @@ 尽量减少操作次数。 -# 思路 +## 思路 做这道题目之前,大家可以做一做[27.移除元素](https://programmercarl.com/0027.移除元素.html) @@ -58,9 +55,9 @@ public: }; ``` -# 其他语言版本 +## 其他语言版本 -Java: +### Java: ```java public void moveZeroes(int[] nums) { @@ -77,7 +74,7 @@ public void moveZeroes(int[] nums) { } ``` -Python: +### Python: ```python def moveZeroes(self, nums: List[int]) -> None: @@ -100,7 +97,7 @@ Python: fast += 1 ``` -Go: +### Go: ```go func moveZeroes(nums []int) { @@ -116,7 +113,8 @@ func moveZeroes(nums []int) { } ``` -JavaScript: +### JavaScript: + ```javascript var moveZeroes = function(nums) { let slow = 0; @@ -133,7 +131,7 @@ var moveZeroes = function(nums) { }; ``` -TypeScript: +### TypeScript: ```typescript function moveZeroes(nums: number[]): void { @@ -159,3 +157,4 @@ function moveZeroes(nums: number[]): void { + diff --git a/problems/0463.岛屿的周长.md b/problems/0463.岛屿的周长.md index 18f1d01e..14fa98dc 100644 --- a/problems/0463.岛屿的周长.md +++ b/problems/0463.岛屿的周长.md @@ -90,7 +90,7 @@ public: ## 其他语言版本 -Java: +### Java: ```java // 解法一 @@ -191,8 +191,8 @@ class Solution { ``` -Python: -### 解法1: +### Python: + 扫描每个cell,如果当前位置为岛屿 grid[i][j] == 1, 从当前位置判断四边方向,如果边界或者是水域,证明有边界存在,res矩阵的对应cell加一。 ```python @@ -228,7 +228,8 @@ class Solution: ``` -Go: +### Go: + ```go func islandPerimeter(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -249,7 +250,8 @@ func islandPerimeter(grid [][]int) int { } ``` -JavaScript: +### JavaScript: + ```javascript //解法一 var islandPerimeter = function(grid) { @@ -305,3 +307,4 @@ var islandPerimeter = function(grid) { + diff --git a/problems/0496.下一个更大元素I.md b/problems/0496.下一个更大元素I.md index 411a47df..6bcafafb 100644 --- a/problems/0496.下一个更大元素I.md +++ b/problems/0496.下一个更大元素I.md @@ -37,7 +37,7 @@ nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位 * nums1和nums2中所有整数 互不相同 * nums1 中的所有整数同样出现在 nums2 中 -# 思路 +## 思路 做本题之前,建议先做一下[739. 每日温度](https://programmercarl.com/0739.每日温度.html) @@ -191,7 +191,8 @@ public: 建议大家把情况一二三想清楚了,先写出版本一的代码,然后在其基础上在做精简! ## 其他语言版本 -Java +### Java + ```java class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { @@ -248,7 +249,8 @@ class Solution { } } ``` -Python3: +### Python3 + ```python class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: @@ -269,7 +271,7 @@ class Solution: return result ``` -Go: +### Go > 未精简版本 ```go @@ -335,7 +337,7 @@ func nextGreaterElement(nums1 []int, nums2 []int) []int { } ``` -JavaScript: +### JavaScript ```JS var nextGreaterElement = function (nums1, nums2) { @@ -358,7 +360,7 @@ var nextGreaterElement = function (nums1, nums2) { }; ``` -TypeScript: +### TypeScript ```typescript function nextGreaterElement(nums1: number[], nums2: number[]): number[] { @@ -387,7 +389,7 @@ function nextGreaterElement(nums1: number[], nums2: number[]): number[] { }; ``` -Rust +### Rust ```rust impl Solution { @@ -419,3 +421,4 @@ impl Solution { + diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md index a090f32c..023e4d7e 100644 --- a/problems/0503.下一个更大元素II.md +++ b/problems/0503.下一个更大元素II.md @@ -22,7 +22,7 @@ * -10^9 <= nums[i] <= 10^9 -# 思路 +## 思路 做本题之前建议先做[739. 每日温度](https://programmercarl.com/0739.每日温度.html) 和 [496.下一个更大元素 I](https://programmercarl.com/0496.下一个更大元素I.html)。 @@ -138,7 +138,8 @@ public: ## 其他语言版本 -Java: +### Java: + ```Java class Solution { public int[] nextGreaterElements(int[] nums) { @@ -162,7 +163,8 @@ class Solution { } ``` -Python: +### Python: + ```python # 方法 1: class Solution: @@ -196,7 +198,8 @@ class Solution: stack.append(i) return ans ``` -Go: +### Go: + ```go func nextGreaterElements(nums []int) []int { length := len(nums) @@ -218,7 +221,7 @@ func nextGreaterElements(nums []int) []int { } ``` -JavaScript: +### JavaScript: ```JS /** @@ -242,7 +245,7 @@ var nextGreaterElements = function (nums) { return res; }; ``` -TypeScript: +### TypeScript: ```typescript function nextGreaterElements(nums: number[]): number[] { @@ -266,7 +269,8 @@ function nextGreaterElements(nums: number[]): number[] { }; ``` -Rust +### Rust: + ```rust impl Solution { pub fn next_greater_elements(nums: Vec) -> Vec { @@ -290,3 +294,4 @@ impl Solution { + diff --git a/problems/0649.Dota2参议院.md b/problems/0649.Dota2参议院.md index a1420a66..db6b43df 100644 --- a/problems/0649.Dota2参议院.md +++ b/problems/0649.Dota2参议院.md @@ -42,7 +42,7 @@ Dota2 参议院由来自两派的参议员组成。现在参议院希望对一 因此在第二轮只剩下第三个参议员拥有投票的权利,于是他可以宣布胜利。 -# 思路 +## 思路 这道题 题意太绕了,我举一个更形象的例子给大家捋顺一下。 @@ -70,7 +70,7 @@ Dota2 参议院由来自两派的参议员组成。现在参议院希望对一 如果对贪心算法理论基础还不了解的话,可以看看这篇:[关于贪心算法,你该了解这些!](https://programmercarl.com/贪心算法理论基础.html) ,相信看完之后对贪心就有基本的了解了。 -# 代码实现 +## 代码实现 实现代码,在每一轮循环的过程中,去过模拟优先消灭身后的对手,其实是比较麻烦的。 @@ -111,9 +111,9 @@ public: -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java class Solution { @@ -145,7 +145,7 @@ class Solution { } ``` -## Python +### Python ```python class Solution: @@ -173,7 +173,7 @@ class Solution: return "Radiant" if R else "Dire" ``` -## Go +### Go ```go @@ -214,7 +214,7 @@ func predictPartyVictory(senateStr string) string { } ``` -## JavaScript +### JavaScript ```js var predictPartyVictory = function(senateStr) { @@ -244,7 +244,7 @@ var predictPartyVictory = function(senateStr) { }; ``` -## TypeScript +### TypeScript ```typescript function predictPartyVictory(senate: string): string { @@ -287,3 +287,4 @@ function predictPartyVictory(senate: string): string { + diff --git a/problems/0657.机器人能否返回原点.md b/problems/0657.机器人能否返回原点.md index ab4bf152..f0d33391 100644 --- a/problems/0657.机器人能否返回原点.md +++ b/problems/0657.机器人能否返回原点.md @@ -29,7 +29,7 @@ -# 思路 +## 思路 这道题目还是挺简单的,大家不要想复杂了,一波哈希法又一波图论算法啥的,哈哈。 @@ -64,9 +64,9 @@ public: ``` -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java // 时间复杂度:O(n) @@ -86,7 +86,7 @@ class Solution { } ``` -## Python +### Python ```python # 时间复杂度:O(n) @@ -107,7 +107,7 @@ class Solution: return x == 0 and y == 0 ``` -## Go +### Go ```go func judgeCircle(moves string) bool { @@ -131,7 +131,7 @@ func judgeCircle(moves string) bool { } ``` -## JavaScript +### JavaScript ```js // 时间复杂度:O(n) @@ -150,7 +150,7 @@ var judgeCircle = function(moves) { ``` -## TypeScript +### TypeScript ```ts var judgeCircle = function (moves) { @@ -185,3 +185,4 @@ var judgeCircle = function (moves) { + diff --git a/problems/0673.最长递增子序列的个数.md b/problems/0673.最长递增子序列的个数.md index da80a4e0..0277f249 100644 --- a/problems/0673.最长递增子序列的个数.md +++ b/problems/0673.最长递增子序列的个数.md @@ -24,7 +24,7 @@ * 解释: 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。 -# 思路 +## 思路 这道题可以说是 [300.最长上升子序列](https://programmercarl.com/0300.最长上升子序列.html) 的进阶版本 @@ -221,9 +221,9 @@ public: 还有O(nlog n)的解法,使用树状数组,今天有点忙就先不写了,感兴趣的同学可以自行学习一下,这里有我之前写的树状数组系列博客:https://blog.csdn.net/youngyangyang04/category_871105.html (十年前的陈年老文了) -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java class Solution { @@ -257,7 +257,7 @@ class Solution { } ``` -## Python +### Python ```python class Solution: @@ -286,7 +286,7 @@ class Solution: return result; ``` -## Go +### Go ```go @@ -332,7 +332,7 @@ func findNumberOfLIS(nums []int) int { } ``` -## JavaScript +### JavaScript ```js var findNumberOfLIS = function(nums) { @@ -364,3 +364,4 @@ var findNumberOfLIS = function(nums) { + diff --git a/problems/0684.冗余连接.md b/problems/0684.冗余连接.md index c4d62d9b..8124cc7e 100644 --- a/problems/0684.冗余连接.md +++ b/problems/0684.冗余连接.md @@ -25,7 +25,7 @@ * edges 中无重复元素 * 给定的图是连通的  -# 思路 +## 思路 这道题目也是并查集基础题目。 @@ -150,9 +150,9 @@ public: 可以看出,主函数的代码很少,就判断一下边的两个节点在不在同一个集合就可以了。 -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java class Solution { @@ -205,7 +205,7 @@ class Solution { } ``` -## Python +### Python ```python @@ -256,7 +256,7 @@ class Solution: return [] ``` -## Go +### Go ```go @@ -312,7 +312,7 @@ func findRedundantConnection(edges [][]int) []int { } ``` -## JavaScript +### JavaScript ```js const n = 1005; @@ -365,3 +365,4 @@ var findRedundantConnection = function(edges) { + diff --git a/problems/0685.冗余连接II.md b/problems/0685.冗余连接II.md index 8c56afdc..31b2ad24 100644 --- a/problems/0685.冗余连接II.md +++ b/problems/0685.冗余连接II.md @@ -213,9 +213,9 @@ public: ``` -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java @@ -335,7 +335,7 @@ class Solution { } ``` -## Python +### Python ```python @@ -426,7 +426,7 @@ class Solution: return self.getRemoveEdge(edges) ``` -## Go +### Go ```go @@ -527,7 +527,7 @@ func findRedundantDirectedConnection(edges [][]int) []int { ``` -## JavaScript +### JavaScript ```js const N = 1010; // 如题:二维数组大小的在3到1000范围内 @@ -623,3 +623,4 @@ var findRedundantDirectedConnection = function(edges) { + diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md index d2da3737..fc1a8063 100644 --- a/problems/0739.每日温度.md +++ b/problems/0739.每日温度.md @@ -211,8 +211,7 @@ public: ## 其他语言版本 - -Java: +### Java: ```java class Solution { @@ -270,7 +269,8 @@ class Solution { } ``` -Python: +### Python: + > 未精简版本 ```python @@ -307,7 +307,7 @@ class Solution: return answer ``` -Go: +### Go: > 暴力法 @@ -384,7 +384,7 @@ func dailyTemperatures(num []int) []int { } ``` -JavaScript: +### JavaScript: ```javascript // 版本一 @@ -429,7 +429,7 @@ var dailyTemperatures = function(temperatures) { }; ``` -TypeScript: +### TypeScript: > 精简版: @@ -455,7 +455,7 @@ function dailyTemperatures(temperatures: number[]): number[] { }; ``` -Rust: +### Rust: ```rust impl Solution { @@ -482,3 +482,4 @@ impl Solution { + diff --git a/problems/0922.按奇偶排序数组II.md b/problems/0922.按奇偶排序数组II.md index c4654f16..72be8fa7 100644 --- a/problems/0922.按奇偶排序数组II.md +++ b/problems/0922.按奇偶排序数组II.md @@ -147,8 +147,6 @@ class Solution { } ``` -### java - ```java //方法一:采用额外的数组空间 class Solution { @@ -384,3 +382,4 @@ function sortArrayByParityII(nums: number[]): number[] { + diff --git a/problems/0941.有效的山脉数组.md b/problems/0941.有效的山脉数组.md index f43a2108..48c29eb4 100644 --- a/problems/0941.有效的山脉数组.md +++ b/problems/0941.有效的山脉数组.md @@ -33,7 +33,7 @@ * 输出:true -# 思路 +## 思路 判断是山峰,主要就是要严格的保存左边到中间,和右边到中间是递增的。 @@ -71,9 +71,9 @@ public: 如果想系统学一学双指针的话, 可以看一下这篇[双指针法:总结篇!](https://programmercarl.com/双指针总结.html) -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java class Solution { @@ -101,7 +101,7 @@ class Solution { } ``` -## Python3 +### Python3 ```python class Solution: @@ -118,7 +118,7 @@ class Solution: ``` -## Go +### Go ```go func validMountainArray(arr []int) bool { @@ -142,7 +142,7 @@ func validMountainArray(arr []int) bool { } ``` -## JavaScript +### JavaScript ```js var validMountainArray = function(arr) { @@ -157,7 +157,7 @@ var validMountainArray = function(arr) { }; ``` -## TypeScript +### TypeScript ```typescript function validMountainArray(arr: number[]): boolean { @@ -177,7 +177,7 @@ function validMountainArray(arr: number[]): boolean { }; ``` -## C# +### C# ```csharp public class Solution { @@ -201,3 +201,4 @@ public class Solution { + diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index a53148b3..1138d7fc 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -30,7 +30,7 @@ words[i] 由小写英文字母组成 -# 思路 +## 思路 这道题意一起就有点绕,不是那么容易懂,其实就是26个小写字符中有字符 在所有字符串里都出现的话,就输出,重复的也算。 @@ -140,7 +140,7 @@ public: ## 其他语言版本 -Java: +### Java: ```Java class Solution { @@ -174,7 +174,8 @@ class Solution { } } ``` -Python +### Python + ```python class Solution: def commonChars(self, words: List[str]) -> List[str]: @@ -218,7 +219,8 @@ class Solution: return l ``` -javaScript +### JavaScript + ```js var commonChars = function (words) { let res = [] @@ -285,7 +287,8 @@ var commonChars = function(words) { } ``` -TypeScript +### TypeScript + ```ts console.time("test") let str: string = "" @@ -321,7 +324,8 @@ TypeScript return str.split("") ``` -GO +### GO + ```golang func commonChars(words []string) []string { length:=len(words) @@ -357,7 +361,8 @@ func min(a,b int)int{ } ``` -Swift: +### Swift: + ```swift func commonChars(_ words: [String]) -> [String] { var res = [String]() @@ -397,7 +402,8 @@ func commonChars(_ words: [String]) -> [String] { } ``` -C: +### C: + ```c //若两个哈希表定义为char数组(每个单词的最大长度不会超过100,因此可以用char表示),可以提高时间和空间效率 void updateHashTable(int* hashTableOne, int* hashTableTwo) { @@ -449,7 +455,8 @@ char ** commonChars(char ** words, int wordsSize, int* returnSize){ return ret; } ``` -Scala: +### Scala: + ```scala object Solution { def commonChars(words: Array[String]): List[String] = { @@ -483,7 +490,7 @@ object Solution { } ``` -Rust: +### Rust: ```rust impl Solution { @@ -522,3 +529,4 @@ impl Solution { + diff --git a/problems/1207.独一无二的出现次数.md b/problems/1207.独一无二的出现次数.md index 1a7a0019..83ebbcb7 100644 --- a/problems/1207.独一无二的出现次数.md +++ b/problems/1207.独一无二的出现次数.md @@ -31,7 +31,7 @@ * -1000 <= arr[i] <= 1000 -# 思路 +## 思路 这道题目数组在是哈希法中的经典应用,如果对数组在哈希法中的使用还不熟悉的同学可以看这两篇:[数组在哈希法中的应用](https://programmercarl.com/0242.有效的字母异位词.html)和[哈希法:383. 赎金信](https://programmercarl.com/0383.赎金信.html) @@ -71,9 +71,9 @@ public: }; ``` -# 其他语言版本 +## 其他语言版本 -Java: +### Java: ```java class Solution { @@ -97,7 +97,8 @@ class Solution { } ``` -Python: +### Python: + ```python # 方法 1: 数组在哈西法的应用 class Solution: @@ -133,10 +134,8 @@ class Solution: ``` +### JavaScript: -Go: - -JavaScript: ``` javascript // 方法一:使用数组记录元素出现次数 var uniqueOccurrences = function(arr) { @@ -171,7 +170,7 @@ var uniqueOccurrences = function(arr) { }; ``` -TypeScript: +### TypeScript: > 借用数组: @@ -209,3 +208,4 @@ function uniqueOccurrences(arr: number[]): boolean { + diff --git a/problems/1356.根据数字二进制下1的数目排序.md b/problems/1356.根据数字二进制下1的数目排序.md index b898b7f2..cc7a7007 100644 --- a/problems/1356.根据数字二进制下1的数目排序.md +++ b/problems/1356.根据数字二进制下1的数目排序.md @@ -46,7 +46,7 @@ -# 思路 +## 思路 这道题其实是考察如何计算一个数的二进制中1的数量。 @@ -87,7 +87,7 @@ int bitCount(int n) { 下面我就使用方法二,来做这道题目: -## C++代码 + ```C++ class Solution { @@ -116,9 +116,9 @@ public: -# 其他语言版本 +## 其他语言版本 -## Java +### Java ```java class Solution { @@ -151,7 +151,7 @@ class Solution { -## Python +### Python ```python class Solution: @@ -167,7 +167,7 @@ class Solution: return count ``` -## Go +### Go ```go func sortByBits(arr []int) []int { @@ -205,7 +205,7 @@ func bitCount(n int) int { } ``` -## JavaScript +### JavaScript ```js var sortByBits = function(arr) { @@ -227,3 +227,4 @@ var sortByBits = function(arr) { + diff --git a/problems/1365.有多少小于当前数字的数字.md b/problems/1365.有多少小于当前数字的数字.md index 7c268769..c706ba21 100644 --- a/problems/1365.有多少小于当前数字的数字.md +++ b/problems/1365.有多少小于当前数字的数字.md @@ -39,7 +39,7 @@ * 2 <= nums.length <= 500 * 0 <= nums[i] <= 100 -# 思路 +## 思路 两层for循环暴力查找,时间复杂度明显为$O(n^2)$。 @@ -113,9 +113,9 @@ public: 可以排序之后加哈希,时间复杂度为$O(n\log n)$ -# 其他语言版本 +## 其他语言版本 -Java: +### Java: ```Java public int[] smallerNumbersThanCurrent(int[] nums) { @@ -136,7 +136,8 @@ public int[] smallerNumbersThanCurrent(int[] nums) { } ``` -Python: +### Python: + ```python class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: @@ -151,7 +152,8 @@ class Solution: return res ``` -Go: +### Go: + ```go func smallerNumbersThanCurrent(nums []int) []int { // map,key[数组中出现的数] value[比这个数小的个数] @@ -180,7 +182,8 @@ func smallerNumbersThanCurrent(nums []int) []int { } ``` -JavaScript: +### JavaScript: + ```javascript // 方法一:使用哈希表记录位置 var smallerNumbersThanCurrent = function(nums) { @@ -217,7 +220,7 @@ var smallerNumbersThanCurrent = function(nums) { }; ``` -TypeScript: +### TypeScript: > 暴力法: diff --git a/problems/1382.将二叉搜索树变平衡.md b/problems/1382.将二叉搜索树变平衡.md index 0f81745c..57e56b8f 100644 --- a/problems/1382.将二叉搜索树变平衡.md +++ b/problems/1382.将二叉搜索树变平衡.md @@ -28,7 +28,7 @@ * 树节点的数目在 1 到 10^4 之间。 * 树节点的值互不相同,且在 1 到 10^5 之间。 -# 思路 +## 思路 这道题目,可以中序遍历把二叉树转变为有序数组,然后在根据有序数组构造平衡二叉搜索树。 @@ -71,9 +71,10 @@ public: }; ``` -# 其他语言版本 +## 其他语言版本 + +### Java: -Java: ```java class Solution { ArrayList res = new ArrayList(); @@ -99,7 +100,8 @@ class Solution { } } ``` -Python: +### Python: + ```python class Solution: def balanceBST(self, root: TreeNode) -> TreeNode: @@ -121,7 +123,7 @@ class Solution: traversal(root) return getTree(res, 0, len(res) - 1) ``` -Go: +### Go: ```go /** @@ -163,7 +165,8 @@ func balanceBST(root *TreeNode) *TreeNode { ``` -JavaScript: +### JavaScript: + ```javascript var balanceBST = function(root) { const res = []; @@ -188,7 +191,7 @@ var balanceBST = function(root) { }; ``` -TypeScript: +### TypeScript: ```typescript function balanceBST(root: TreeNode | null): TreeNode | null { @@ -218,3 +221,4 @@ function buildTree(arr: number[], left: number, right: number): TreeNode | null + diff --git a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md index a488c0ba..8be48f38 100644 --- a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md +++ b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md @@ -13,7 +13,7 @@ 计算机究竟1s可以执行多少次操作呢? 接下来探讨一下这个问题。 -# 超时是怎么回事 +## 超时是怎么回事 ![程序超时](https://code-thinking-1253855093.file.myqcloud.com/pics/20200729112716117.png) @@ -25,7 +25,7 @@ 如果n的规模已经足够让O(n)的算法运行时间超过了1s,就应该考虑log(n)的解法了。 -# 从硬件配置看计算机的性能 +## 从硬件配置看计算机的性能 计算机的运算速度主要看CPU的配置,以2015年MacPro为例,CPU配置:2.7 GHz Dual-Core Intel Core i5 。 @@ -44,7 +44,7 @@ 所以我们的程序在计算机上究竟1s真正能执行多少次操作呢? -# 做个测试实验 +## 做个测试实验 在写测试程序测1s内处理多大数量级数据的时候,有三点需要注意: @@ -155,7 +155,7 @@ O(nlogn)的算法,1s内大概计算机可以运行 2 * (10^7)次计算,符 至于O(log n)和O(n^3) 等等这些时间复杂度在1s内可以处理的多大的数据规模,大家可以自己写一写代码去测一下了。 -# 完整测试代码 +## 完整测试代码 ```CPP #include @@ -212,7 +212,7 @@ int main() { ``` -# 总结 +## 总结 本文详细分析了在leetcode上做题程序为什么会有超时,以及从硬件配置上大体知道CPU的执行速度,然后亲自做一个实验来看看O(n)的算法,跑一秒钟,这个n究竟是做大,最后给出不同时间复杂度,一秒内可以运算出来的n的大小。 @@ -220,17 +220,6 @@ int main() { 这样,大家应该对程序超时时候的数据规模有一个整体的认识了。 -## 其他语言版本 - - -Java: - - -Python: - - -Go: - @@ -238,3 +227,4 @@ Go: + diff --git a/problems/关于时间复杂度,你不知道的都在这里!.md b/problems/关于时间复杂度,你不知道的都在这里!.md index c479dddc..95c7567c 100644 --- a/problems/关于时间复杂度,你不知道的都在这里!.md +++ b/problems/关于时间复杂度,你不知道的都在这里!.md @@ -8,6 +8,8 @@ 所以重新整理的时间复杂度文章,正式和大家见面啦! +# 时间复杂度 + ## 究竟什么是时间复杂度 **时间复杂度是一个函数,它定性描述该算法的运行时间**。 @@ -145,7 +147,7 @@ O(2 × n^2 + 10 × n + 1000) < O(3 × n^2),所以说最后省略掉常数项 **当然这不是这道题目的最优解,我仅仅是用这道题目来讲解一下时间复杂度**。 -# 总结 +## 总结 本篇讲解了什么是时间复杂度,复杂度是用来干什么,以及数据规模对时间复杂度的影响。 @@ -157,17 +159,6 @@ O(2 × n^2 + 10 × n + 1000) < O(3 × n^2),所以说最后省略掉常数项 如果感觉「代码随想录」很不错,赶快推荐给身边的朋友同学们吧,他们发现和「代码随想录」相见恨晚! -## 其他语言版本 - - -Java: - - -Python: - - -Go: - @@ -175,3 +166,4 @@ Go: +