Merge branch 'master' of github.com:lzxjack/leetcode-master

This commit is contained in:
Jack
2021-08-03 08:45:46 +08:00
16 changed files with 551 additions and 114 deletions

View File

@ -99,6 +99,24 @@ public:
## Java
```java
class Solution {
public void nextPermutation(int[] nums) {
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = nums.length - 1; j > i; j--) {
if (nums[j] > nums[i]) {
// 交换
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
// [i + 1, nums.length) 内元素升序排序
Arrays.sort(nums, i + 1, nums.length);
return;
}
}
}
Arrays.sort(nums); // 不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
}
}
```
## Python

View File

@ -223,7 +223,7 @@ class Solution {
// 解法2
// 1、首先在 nums 数组中二分查找 target
// 2、如果二分查找失败则 binarySearch 返回 -1表明 nums 中没有 target。此时searchRange 直接返回 {-1, -1}
// 3、如果二分查找失败,则 binarySearch 返回 nums 中 为 target 的一个下标。然后,通过左右滑动指针,来找到符合题意的区间
// 3、如果二分查找成功,则 binarySearch 返回 nums 中为 target 的一个下标。然后,通过左右滑动指针,来找到符合题意的区间
class Solution {
public int[] searchRange(int[] nums, int target) {

View File

@ -654,43 +654,68 @@ class Solution {
```
Python
105.从前序与中序遍历序列构造二叉树
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
//递归法
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not preorder: return None //特殊情况
root = TreeNode(preorder[0]) //新建父节点
p=inorder.index(preorder[0]) //找到父节点在中序遍历的位置(因为没有重复的元素,才可以这样找)
root.left = self.buildTree(preorder[1:p+1],inorder[:p]) //注意左节点时分割中序数组和前续数组的开闭环
root.right = self.buildTree(preorder[p+1:],inorder[p+1:]) //分割中序数组和前续数组
return root
# 第一步: 特殊情况讨论: 树为空. 或者说是递归终止条件
if not preorder:
return None
# 第二步: 前序遍历的第一个就是当前的中间节点.
root_val = preorder[0]
root = TreeNode(root_val)
# 第三步: 找切割点.
separator_idx = inorder.index(root_val)
# 第四步: 切割inorder数组. 得到inorder数组的左,右半边.
inorder_left = inorder[:separator_idx]
inorder_right = inorder[separator_idx + 1:]
# 第五步: 切割preorder数组. 得到preorder数组的左,右半边.
# ⭐️ 重点1: 中序数组大小一定跟前序数组大小是相同的.
preorder_left = preorder[1:1 + len(inorder_left)]
preorder_right = preorder[1 + len(inorder_left):]
# 第六步: 递归
root.left = self.buildTree(preorder_left, inorder_left)
root.right = self.buildTree(preorder_right, inorder_right)
return root
```
106.从中序与后序遍历序列构造二叉树
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
//递归法
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not postorder: return None //特殊情况
root = TreeNode(postorder[-1]) //新建父节点
p=inorder.index(postorder[-1]) //找到父节点在中序遍历的位置*因为没有重复的元素,才可以这样找
root.left = self.buildTree(inorder[:p],postorder[:p]) //分割中序数组和后续数组
root.right = self.buildTree(inorder[p+1:],postorder[p:-1]) //注意右节点时分割中序数组和后续数组的开闭环
return root
# 第一步: 特殊情况讨论: 树为空. (递归终止条件)
if not postorder:
return None
# 第二步: 后序遍历的最后一个就是当前的中间节点.
root_val = postorder[-1]
root = TreeNode(root_val)
# 第三步: 找切割点.
separator_idx = inorder.index(root_val)
# 第四步: 切割inorder数组. 得到inorder数组的左,右半边.
inorder_left = inorder[:separator_idx]
inorder_right = inorder[separator_idx + 1:]
# 第五步: 切割postorder数组. 得到postorder数组的左,右半边.
# ⭐️ 重点1: 中序数组大小一定跟后序数组大小是相同的.
postorder_left = postorder[:len(inorder_left)]
postorder_right = postorder[len(inorder_left): len(postorder) - 1]
# 第六步: 递归
root.left = self.buildTree(inorder_left, postorder_left)
root.right = self.buildTree(inorder_right, postorder_right)
return root
```
Go
> 106 从中序与后序遍历序列构造二叉树

View File

@ -416,6 +416,8 @@ class Solution {
Python
0112.路径总和
**递归**
```python
# Definition for a binary tree node.
# class TreeNode:
@ -424,28 +426,56 @@ Python
# self.left = left
# self.right = right
// 递归法
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
def isornot(root,targetSum)->bool:
if (not root.left) and (not root.right) and targetSum == 0:return True // 遇到叶子节点并且计数为0
if (not root.left) and (not root.right):return False //遇到叶子节点,计数为0
def isornot(root, targetSum) -> bool:
if (not root.left) and (not root.right) and targetSum == 0:
return True # 遇到叶子节点,并且计数为0
if (not root.left) and (not root.right):
return False # 遇到叶子节点计数不为0
if root.left:
targetSum -= root.left.val //左节点
if isornot(root.left,targetSum):return True //递归,处理左节点
targetSum += root.left.val //回溯
targetSum -= root.left.val # 左节点
if isornot(root.left, targetSum): return True # 递归,处理左节点
targetSum += root.left.val # 回溯
if root.right:
targetSum -= root.right.val //右节点
if isornot(root.right,targetSum):return True //递归,处理右节点
targetSum += root.right.val //回溯
targetSum -= root.right.val # 右节点
if isornot(root.right, targetSum): return True # 递归,处理右节点
targetSum += root.right.val # 回溯
return False
if root == None:return False //别忘记处理空TreeNode
else:return isornot(root,targetSum-root.val)
if root == None:
return False # 别忘记处理空TreeNode
else:
return isornot(root, targetSum - root.val)
```
**迭代 - 层序遍历**
```python
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
if not root:
return False
stack = [] # [(当前节点,路径数值), ...]
stack.append((root, root.val))
while stack:
cur_node, path_sum = stack.pop()
if not cur_node.left and not cur_node.right and path_sum == targetSum:
return True
if cur_node.right:
stack.append((cur_node.right, path_sum + cur_node.right.val))
if cur_node.left:
stack.append((cur_node.left, path_sum + cur_node.left.val))
return False
```
0113.路径总和-ii
**递归**
```python
# Definition for a binary tree node.
# class TreeNode:
@ -453,35 +483,36 @@ class Solution:
# self.val = val
# self.left = left
# self.right = right
//递归法
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
path=[]
res=[]
def pathes(root,targetSum):
if (not root.left) and (not root.right) and targetSum == 0: // 遇到叶子节点并且计数为0
res.append(path[:]) //找到一种路径记录到res中注意必须是path[:]而不是path
return
if (not root.left) and (not root.right):return // 遇到叶子节点直接返回
if root.left: //左
targetSum -= root.left.val
path.append(root.left.val) //递归前记录节点
pathes(root.left,targetSum) //递归
targetSum += root.left.val //回溯
path.pop() //回溯
if root.right: //右
targetSum -= root.right.val
path.append(root.right.val) //递归前记录节点
pathes(root.right,targetSum) //递归
targetSum += root.right.val //回溯
path.pop() //回溯
return
if root == None:return [] //处理空TreeNode
else:
path.append(root.val) //首先处理根节点
pathes(root,targetSum-root.val)
return res
def traversal(cur_node, remain):
if not cur_node.left and not cur_node.right and remain == 0:
result.append(path[:])
return
if not cur_node.left and not cur_node.right: return
if cur_node.left:
path.append(cur_node.left.val)
remain -= cur_node.left.val
traversal(cur_node.left, remain)
path.pop()
remain += cur_node.left.val
if cur_node.right:
path.append(cur_node.right.val)
remain -= cur_node.right.val
traversal(cur_node.right, remain)
path.pop()
remain += cur_node.right.val
result, path = [], []
if not root:
return []
path.append(root.val)
traversal(root, targetSum - root.val)
return result
```
Go

View File

@ -1,4 +1,3 @@
<p align="center">
<a href="https://mp.weixin.qq.com/s/RsdcQ9umo09R6cfnwXZlrQ"><img src="https://img.shields.io/badge/PDF下载-代码随想录-blueviolet" alt=""></a>
<a href="https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw"><img src="https://img.shields.io/badge/刷题-微信群-green" alt=""></a>
@ -63,6 +62,7 @@ public:
## 方法二
把链表放进双向队列,然后通过双向队列一前一后弹出数据,来构造新的链表。这种方法比操作数组容易一些,不用双指针模拟一前一后了
```C++
class Solution {
public:
@ -176,6 +176,51 @@ public:
Java
```java
public class ReorderList {
public void reorderList(ListNode head) {
ListNode fast = head, slow = head;
//求出中点
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
//right就是右半部分 12345 就是45 1234 就是34
ListNode right = slow.next;
//断开左部分和右部分
slow.next = null;
//反转右部分 right就是反转后右部分的起点
right = reverseList(right);
//左部分的起点
ListNode left = head;
//进行左右部分来回连接
//这里左部分的节点个数一定大于等于右部分的节点个数 因此只判断right即可
while (right != null) {
ListNode curLeft = left.next;
left.next = right;
left = curLeft;
ListNode curRight = right.next;
right.next = left;
right = curRight;
}
}
public ListNode reverseList(ListNode head) {
ListNode headNode = new ListNode(0);
ListNode cur = head;
ListNode next = null;
while (cur != null) {
next = cur.next;
cur.next = headNode.next;
headNode.next = cur;
cur = next;
}
return headNode.next;
}
}
```
Python
Go
@ -183,8 +228,10 @@ Go
JavaScript
-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
* B站视频[代码随想录](https://space.bilibili.com/525438321)
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -68,6 +68,25 @@ public:
## Java
```java
class Solution {
public boolean isIsomorphic(String s, String t) {
Map<Character, Character> map1 = new HashMap<>();
Map<Character, Character> map2 = new HashMap<>();
for (int i = 0, j = 0; i < s.length(); i++, j++) {
if (!map1.containsKey(s.charAt(i))) {
map1.put(s.charAt(i), t.charAt(j)); // map1保存 s[i] 到 t[j]的映射
}
if (!map2.containsKey(t.charAt(j))) {
map2.put(t.charAt(j), s.charAt(i)); // map2保存 t[j] 到 s[i]的映射
}
// 无法映射,返回 false
if (map1.get(s.charAt(i)) != t.charAt(j) || map2.get(t.charAt(j)) != s.charAt(i)) {
return false;
}
}
return true;
}
}
```
## Python

View File

@ -275,7 +275,50 @@ var reverseList = function(head) {
};
```
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
```
-----------------------

View File

@ -384,7 +384,7 @@ func (this *MyQueue) Peek() int {
func (this *MyQueue) Empty() bool {
return len(this.stack) == 0 && len(this.back) == 0
}
```
javaScript:
@ -442,8 +442,6 @@ MyQueue.prototype.empty = function() {
```
-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
* B站视频[代码随想录](https://space.bilibili.com/525438321)

View File

@ -205,25 +205,51 @@ class Solution {
Python
```Python
**递归**
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
```python
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
self.res=0
def areleftleaves(root):
if not root:return
if root.left and (not root.left.left) and (not root.left.right):self.res+=root.left.val
areleftleaves(root.left)
areleftleaves(root.right)
areleftleaves(root)
return self.res
if not root:
return 0
left_left_leaves_sum = self.sumOfLeftLeaves(root.left) # 左
right_left_leaves_sum = self.sumOfLeftLeaves(root.right) # 右
cur_left_leaf_val = 0
if root.left and not root.left.left and not root.left.right:
cur_left_leaf_val = root.left.val # 中
return cur_left_leaf_val + left_left_leaves_sum + right_left_leaves_sum
```
**迭代**
```python
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
"""
Idea: Each time check current node's left node.
If current node don't have one, skip it.
"""
stack = []
if root:
stack.append(root)
res = 0
while stack:
# 每次都把当前节点的左节点加进去.
cur_node = stack.pop()
if cur_node.left and not cur_node.left.left and not cur_node.left.right:
res += cur_node.left.val
if cur_node.left:
stack.append(cur_node.left)
if cur_node.right:
stack.append(cur_node.right)
return res
```
Go
> 递归法

View File

@ -274,27 +274,51 @@ class Solution {
Python
**递归 - 回溯**
```python
//递归法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findBottomLeftValue(self, root: TreeNode) -> int:
depth=0
self.res=[]
def level(root,depth):
if not root:return
if depth==len(self.res):
self.res.append([])
self.res[depth].append(root.val)
level(root.left,depth+1)
level(root.right,depth+1)
level(root,depth)
return self.res[-1][0]
max_depth = -float("INF")
leftmost_val = 0
def __traverse(root, cur_depth):
nonlocal max_depth, leftmost_val
if not root.left and not root.right:
if cur_depth > max_depth:
max_depth = cur_depth
leftmost_val = root.val
if root.left:
cur_depth += 1
__traverse(root.left, cur_depth)
cur_depth -= 1
if root.right:
cur_depth += 1
__traverse(root.right, cur_depth)
cur_depth -= 1
__traverse(root, 0)
return leftmost_val
```
**迭代 - 层序遍历**
```python
class Solution:
def findBottomLeftValue(self, root: TreeNode) -> int:
queue = deque()
if root:
queue.append(root)
result = 0
while queue:
q_len = len(queue)
for i in range(q_len):
if i == 0:
result = queue[i].val
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return result
```
Go

View File

@ -71,21 +71,84 @@ public:
## Java
```java
// 时间复杂度O(n)
// 空间复杂度:如果采用 toCharArray则是 On;如果使用 charAt则是 O(1)
class Solution {
public boolean judgeCircle(String moves) {
int x = 0;
int y = 0;
for (char c : moves.toCharArray()) {
if (c == 'U') y++;
if (c == 'D') y--;
if (c == 'L') x++;
if (c == 'R') x--;
}
return x == 0 && y == 0;
}
}
```
## Python
```python
# 时间复杂度O(n)
# 空间复杂度O(1)
class Solution:
def judgeCircle(self, moves: str) -> bool:
x = 0 # 记录当前位置
y = 0
for i in range(len(moves)):
if (moves[i] == 'U'):
y += 1
if (moves[i] == 'D'):
y -= 1
if (moves[i] == 'L'):
x += 1
if (moves[i] == 'R'):
x -= 1
return x == 0 and y == 0
```
## Go
```go
func judgeCircle(moves string) bool {
x := 0
y := 0
for i := 0; i < len(moves); i++ {
if moves[i] == 'U' {
y++
}
if moves[i] == 'D' {
y--
}
if moves[i] == 'L' {
x++
}
if moves[i] == 'R' {
x--
}
}
return x == 0 && y == 0;
}
```
## JavaScript
```js
// 时间复杂度O(n)
// 空间复杂度O(1)
var judgeCircle = function(moves) {
var x = 0; // 记录当前位置
var y = 0;
for (var i = 0; i < moves.length; i++) {
if (moves[i] == 'U') y++;
if (moves[i] == 'D') y--;
if (moves[i] == 'L') x++;
if (moves[i] == 'R') x--;
}
return x == 0 && y == 0;
};
```
-----------------------

View File

@ -235,8 +235,6 @@ class Solution:
return -1
```
**Go**
(版本一)左闭右闭区间
@ -279,7 +277,7 @@ func search(nums []int, target int) int {
}
```
**javaScript:**
**JavaScript:**
```js
@ -316,7 +314,43 @@ var search = function(nums, target) {
```
**Ruby:**
```ruby
# (版本一)左闭右闭区间
def search(nums, target)
left, right = 0, nums.length - 1
while left <= right # 由于定义target在一个在左闭右闭的区间里因此极限情况下存在left==right
middle = (left + right) / 2
if nums[middle] > target
right = middle - 1
elsif nums[middle] < target
left = middle + 1
else
return middle # return兼具返回与跳出循环的作用
end
end
-1
end
# (版本二)左闭右开区间
def search(nums, target)
left, right = 0, nums.length
while left < right # 由于定义target在一个在左闭右开的区间里因此极限情况下right=left+1
middle = (left + right) / 2
if nums[middle] > target
right = middle
elsif nums[middle] < target
left = middle + 1
else
return middle
end
end
-1
end
```

View File

@ -67,6 +67,24 @@ public:
## Java
```java
class Solution {
public int pivotIndex(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i]; // 总和
}
int leftSum = 0;
int rightSum = 0;
for (int i = 0; i < nums.length; i++) {
leftSum += nums[i];
rightSum = sum - leftSum + nums[i]; // leftSum 里面已经有 nums[i],多减了一次,所以加上
if (leftSum == rightSum) {
return i;
}
}
return -1; // 不存在
}
}
```
## Python
@ -90,4 +108,3 @@ public:
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -14,7 +14,7 @@
给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。
注意:如果对空文本输入退格字符,文本继续为空。
 
示例 1
* 输入S = "ab#c", T = "ad#c"
* 输出true
@ -160,6 +160,32 @@ public:
Java
```java
// 普通方法(使用栈的思路)
class Solution {
public boolean backspaceCompare(String s, String t) {
StringBuilder ssb = new StringBuilder(); // 模拟栈
StringBuilder tsb = new StringBuilder(); // 模拟栈
// 分别处理两个 String
for (char c : s.toCharArray()) {
if (c != '#') {
ssb.append(c); // 模拟入栈
} else if (ssb.length() > 0){ // 栈非空才能弹栈
ssb.deleteCharAt(ssb.length() - 1); // 模拟弹栈
}
}
for (char c : t.toCharArray()) {
if (c != '#') {
tsb.append(c); // 模拟入栈
} else if (tsb.length() > 0){ // 栈非空才能弹栈
tsb.deleteCharAt(tsb.length() - 1); // 模拟弹栈
}
}
return ssb.toString().equals(tsb.toString());
}
}
```
Python
Go

View File

@ -120,6 +120,31 @@ public:
## Java
```java
// 方法一
class Solution {
public int[] sortArrayByParityII(int[] nums) {
// 分别存放 nums 中的奇数、偶数
int len = nums.length;
int evenIndex = 0;
int oddIndex = 0;
int[] even = new int[len / 2];
int[] odd = new int[len / 2];
for (int i = 0; i < len; i++) {
if (nums[i] % 2 == 0) {
even[evenIndex++] = nums[i];
} else {
odd[oddIndex++] = nums[i];
}
}
// 把奇偶数组重新存回 nums
int index = 0;
for (int i = 0; i < even.length; i++) {
nums[index++] = even[i];
nums[index++] = odd[i];
}
return nums;
}
}
```
## Python
@ -143,4 +168,3 @@ public:
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -16,7 +16,7 @@
换而言之对于每个 nums[i] 你必须计算出有效的 j 的数量其中 j 满足 j != i 且 nums[j] < nums[i] 
以数组形式返回答案
 
示例 1
输入nums = [8,1,2,2,3]
@ -35,7 +35,7 @@
示例 3
输入nums = [7,7,7,7]
输出[0,0,0,0]
 
提示
* 2 <= nums.length <= 500
* 0 <= nums[i] <= 100
@ -120,8 +120,51 @@ public:
## Java
```java
/**
* 解法一:暴力
* 时间复杂度O(n^2)
* 空间复杂度O(n)
*/
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (nums[j] < nums[i] && j != i) { // 注意 j 不能和 i 重合
res[i]++;
}
}
}
return res;
}
}
```
```java
/**
* 优化:排序 + 哈希表
* 时间复杂度O(nlogn)
* 空间复杂度O(n)
*/
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] res = Arrays.copyOf(nums, nums.length);
Arrays.sort(res); // 是对 res 排序nums 中顺序还要保持
int[] hash = new int[101]; // 使用哈希表,记录比当前元素小的元素个数
for (int i = res.length - 1; i >= 0; i--) { // 注意:从后向前
hash[res[i]] = i; // 排序后,当前下标即表示比当前元素小的元素个数
}
// 此时 hash中保存的每一个元素数值 便是 小于这个数值的个数
for (int i = 0; i < res.length; i++) {
res[i] = hash[nums[i]];
}
return res;
}
}
```
## Python
```python
@ -143,4 +186,3 @@ public:
* 知识星球[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>