This commit is contained in:
youngyangyang04
2021-05-23 11:11:32 +08:00
38 changed files with 1498 additions and 51 deletions

View File

@ -218,8 +218,33 @@ class Solution {
```
Python
```Python
class Solution:
def threeSum(self, nums):
ans = []
n = len(nums)
nums.sort()
for i in range(n):
left = i + 1
right = n - 1
if nums[i] > 0:
break
if i >= 1 and nums[i] == nums[i - 1]:
continue
while left < right:
total = nums[i] + nums[left] + nums[right]
if total > 0:
right -= 1
elif total < 0:
left += 1
else:
ans.append([nums[i], nums[left], nums[right]])
while left != right and nums[left] == nums[left + 1]: left += 1
while left != right and nums[right] == nums[right - 1]: right -= 1
left += 1
right -= 1
return ans
```
Go
```Go
func threeSum(nums []int)[][]int{
@ -256,6 +281,59 @@ func threeSum(nums []int)[][]int{
}
```
javaScript:
```js
/**
* @param {number[]} nums
* @return {number[][]}
*/
// 循环内不考虑去重
var threeSum = function(nums) {
const len = nums.length;
if(len < 3) return [];
nums.sort((a, b) => a - b);
const resSet = new Set();
for(let i = 0; i < len - 2; i++) {
if(nums[i] > 0) break;
let l = i + 1, r = len - 1;
while(l < r) {
const sum = nums[i] + nums[l] + nums[r];
if(sum < 0) { l++; continue };
if(sum > 0) { r--; continue };
resSet.add(`${nums[i]},${nums[l]},${nums[r]}`);
l++;
r--;
}
}
return Array.from(resSet).map(i => i.split(","));
};
// 去重优化
var threeSum = function(nums) {
const len = nums.length;
if(len < 3) return [];
nums.sort((a, b) => a - b);
const res = [];
for(let i = 0; i < len - 2; i++) {
if(nums[i] > 0) break;
// a去重
if(i > 0 && nums[i] === nums[i - 1]) continue;
let l = i + 1, r = len - 1;
while(l < r) {
const sum = nums[i] + nums[l] + nums[r];
if(sum < 0) { l++; continue };
if(sum > 0) { r--; continue };
res.push([nums[i], nums[l], nums[r]])
// b c 去重
while(l < r && nums[l] === nums[++l]);
while(l < r && nums[r] === nums[--r]);
}
}
return res;
};
```

View File

@ -165,11 +165,75 @@ class Solution {
```
Python
```python
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
# use a dict to store value:showtimes
hashmap = dict()
for n in nums:
if n in hashmap:
hashmap[n] += 1
else:
hashmap[n] = 1
# good thing about using python is you can use set to drop duplicates.
ans = set()
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
for k in range(j + 1, len(nums)):
val = target - (nums[i] + nums[j] + nums[k])
if val in hashmap:
# make sure no duplicates.
count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val)
if hashmap[val] > count:
ans.add(tuple(sorted([nums[i], nums[j], nums[k], val])))
else:
continue
return ans
```
Go
javaScript:
```js
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
const len = nums.length;
if(len < 4) return [];
nums.sort((a, b) => a - b);
const res = [];
for(let i = 0; i < len - 3; i++) {
// 去重i
if(i > 0 && nums[i] === nums[i - 1]) continue;
for(let j = i + 1; j < len - 2; j++) {
// 去重j
if(j > i + 1 && nums[j] === nums[j - 1]) continue;
let l = j + 1, r = len - 1;
while(l < r) {
const sum = nums[i] + nums[j] + nums[l] + nums[r];
if(sum < target) { l++; continue}
if(sum > target) { r--; continue}
res.push([nums[i], nums[j], nums[l], nums[r]]);
while(l < r && nums[l] === nums[++l]);
while(l < r && nums[r] === nums[--r]);
}
}
}
return res;
};
```
-----------------------

View File

@ -168,10 +168,49 @@ class Solution {
```
Python
```python
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) == 0: return intervals
intervals.sort(key=lambda x: x[0])
result = []
result.append(intervals[0])
for i in range(1, len(intervals)):
last = result[-1]
if last[1] >= intervals[i][0]:
result[-1] = [last[0], max(last[1], intervals[i][1])]
else:
result.append(intervals[i])
return result
```
Go
```Go
func merge(intervals [][]int) [][]int {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0]<intervals[j][0]
})
res:=[][]int{}
prev:=intervals[0]
for i:=1;i<len(intervals);i++{
cur :=intervals[i]
if prev[1]<cur[0]{
res=append(res,prev)
prev=cur
}else {
prev[1]=max(prev[1],cur[1])
}
}
res=append(res,prev)
return res
}
func max(a, b int) int {
if a > b { return a }
return b
}
```
@ -179,4 +218,4 @@ Go
* 作者微信[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -224,6 +224,49 @@ class Solution:
return matrix
```
javaScript
```js
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
// new Array(n).fill(new Array(n))
// 使用fill --> 填充的是同一个数组地址
const res = Array.from({length: n}).map(() => new Array(n));
let loop = n >> 1, i = 0, //循环次数
count = 1,
startX = startY = 0; // 起始位置
while(++i <= loop) {
// 定义行列
let row = startX, column = startY;
// [ startY, n - i)
while(column < n - i) {
res[row][column++] = count++;
}
// [ startX, n - i)
while(row < n - i) {
res[row++][column] = count++;
}
// [n - i , startY)
while(column > startY) {
res[row][column--] = count++;
}
// [n - i , startX)
while(row > startX) {
res[row--][column] = count++;
}
startX = ++startY;
}
if(n & 1) {
res[startX][startY] = count;
}
return res;
};
```
-----------------------

View File

@ -249,7 +249,24 @@ Python
Go
```Go
func uniquePaths(m int, n int) int {
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, n)
dp[i][0] = 1
}
for j := 0; j < n; j++ {
dp[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
dp[i][j] = dp[i-1][j] + dp[i][j-1]
}
}
return dp[m-1][n-1]
}
```

View File

@ -79,6 +79,35 @@ public:
return result;
}
};
```
javascript代码
```javascript
var levelOrder = function(root) {
//二叉树的层序遍历
let res=[],queue=[];
queue.push(root);
if(root===null){
return res;
}
while(queue.length!==0){
// 记录当前层级节点数
let length=queue.length;
//存放每一层的节点
let curLevel=[];
for(let i=0;i<length;i++){
let node=queue.shift();
curLevel.push(node.val);
// 存放当前层下一层的节点
node.left&&queue.push(node.left);
node.right&&queue.push(node.right);
}
//把每一层的结果放到结果数组
res.push(curLevel);
}
return res;
};
```
**此时我们就掌握了二叉树的层序遍历了那么如下五道leetcode上的题目只需要修改模板的一两行代码不能再多了便可打倒**
@ -122,6 +151,30 @@ public:
}
};
```
javascript代码
```javascript
var levelOrderBottom = function(root) {
let res=[],queue=[];
queue.push(root);
while(queue.length&&root!==null){
// 存放当前层级节点数组
let curLevel=[];
// 计算当前层级节点数量
let length=queue.length;
while(length--){
let node=queue.shift();
// 把当前层节点存入curLevel数组
curLevel.push(node.val);
// 把下一层级的左右节点存入queue队列
node.left&&queue.push(node.left);
node.right&&queue.push(node.right);
}
res.push(curLevel);
}
return res.reverse();
};
```
## 199.二叉树的右视图
@ -159,6 +212,29 @@ public:
}
};
```
javascript代码:
```javascript
var rightSideView = function(root) {
//二叉树右视图 只需要把每一层最后一个节点存储到res数组
let res=[],queue=[];
queue.push(root);
while(queue.length&&root!==null){
// 记录当前层级节点个数
let length=queue.length;
while(length--){
let node=queue.shift();
//length长度为0的时候表明到了层级最后一个节点
if(!length){
res.push(node.val);
}
node.left&&queue.push(node.left);
node.right&&queue.push(node.right);
}
}
return res;
};
```
## 637.二叉树的层平均值
@ -199,6 +275,31 @@ public:
```
javascript代码
```javascript
var averageOfLevels = function(root) {
//层级平均值
let res=[],queue=[];
queue.push(root);
while(queue.length&&root!==null){
//每一层节点个数
let length=queue.length;
//sum记录每一层的和
let sum=0;
for(let i=0;i<length;i++){
let node=queue.shift();
sum+=node.val;
node.left&&queue.push(node.left);
node.right&&queue.push(node.right);
}
//每一层的平均值存入数组res
res.push(sum/length);
}
return res;
};
```
## 429.N叉树的层序遍历
题目链接https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/
@ -250,6 +351,31 @@ public:
};
```
JavaScript代码
```JavaScript
var levelOrder = function(root) {
//每一层可能有2个以上,所以不再使用node.left node.right
let res=[],queue=[];
queue.push(root);
while(queue.length&&root!==null){
//记录每一层节点个数还是和二叉树一致
let length=queue.length;
//存放每层节点 也和二叉树一致
let curLevel=[];
while(length--){
let node = queue.shift();
curLevel.push(node.val);
//这里不再是 ndoe.left node.right 而是循坏node.children
for(let item of node.children){
item&&queue.push(item);
}
}
res.push(curLevel);
}
return res;
};
```
## 515.在每个树行中找最大值
题目链接https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/
@ -287,6 +413,29 @@ public:
}
};
```
javascript代码
```javascript
var largestValues = function(root) {
//使用层序遍历
let res=[],queue=[];
queue.push(root);
while(root!==null&&queue.length){
//设置max初始值就是队列的第一个元素
let max=queue[0];
let length=queue.length;
while(length--){
let node = queue.shift();
max=max>node.val?max:node.val;
node.left&&queue.push(node.left);
node.right&&queue.push(node.right);
}
//把每一层的最大值放到res数组
res.push(max);
}
return res;
};
```
## 116.填充每个节点的下一个右侧节点指针

View File

@ -233,7 +233,27 @@ class Solution {
```
Python
```python3
# 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 sortedArrayToBST(self, nums: List[int]) -> TreeNode:
def buildaTree(left,right):
if left > right: return None #左闭右闭的区间,当区间 left > right的时候就是空节点,当left = right的时候不为空
mid = left + (right - left) // 2 #保证数据不会越界
val = nums[mid]
root = TreeNode(val)
root.left = buildaTree(left,mid - 1)
root.right = buildaTree(mid + 1,right)
return root
root = buildaTree(0,len(nums) - 1) #左闭右闭区间
return root
```
Go
@ -244,4 +264,4 @@ Go
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -201,6 +201,28 @@ Python
Go
javaScript:
```js
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
const ret = new ListNode(0, head);
let cur = ret;
while(cur.next) {
if(cur.next.val === val) {
cur.next = cur.next.next;
continue;
}
cur = cur.next;
}
return ret.next;
};
```

View File

@ -147,6 +147,61 @@ Python
Go
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;
};
```

View File

@ -172,22 +172,51 @@ Python
Go
```go
func minSubArrayLen(target int, nums []int) int {
i := 0
l := len(nums) // 数组长度
sum := 0 // 子数组之和
result := l + 1 // 初始化返回长度为l+1目的是为了判断“不存在符合条件的子数组返回0”的情况
for j := 0; j < l; j++ {
sum += nums[j]
for sum >= target {
subLength := j - i + 1
if subLength < result {
result = subLength
}
sum -= nums[i]
i++
}
}
if result == l+1 {
return 0
} else {
return result
}
}
```
JavaScript:
```
var minSubArrayLen = (target, nums) => {
let left = 0, right = 0,win = Infinity,sum = 0;
while(right < nums.length){
sum += nums[right];
while(sum >= target){
win = right - left + 1 < win? right - left + 1 : win;
sum -= nums[left];
left++;
}
right++;
```js
var minSubArrayLen = function(target, nums) {
// 长度计算一次
const len = nums.length;
let l = r = sum = 0,
res = len + 1; // 子数组最大不会超过自身
while(r < len) {
sum += nums[r++];
// 窗口滑动
while(sum >= target) {
// r始终为开区间 [l, r)
res = res < r - l ? res : r - l;
sum-=nums[l++];
}
}
return win === Infinity? 0:win;
return res > len ? 0 : res;
};
```
@ -195,4 +224,4 @@ var minSubArrayLen = (target, nums) => {
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -247,10 +247,100 @@ func invertTree(root *TreeNode) *TreeNode {
}
```
JavaScript:
使用递归版本的前序遍历
```javascript
var invertTree = function(root) {
//1. 首先使用递归版本的前序遍历实现二叉树翻转
//交换节点函数
const inverNode=function(left,right){
let temp=left;
left=right;
right=temp;
//需要重新给root赋值一下
root.left=left;
root.right=right;
}
//确定递归函数的参数和返回值inverTree=function(root)
//确定终止条件
if(root===null){
return root;
}
//确定节点处理逻辑 交换
inverNode(root.left,root.right);
invertTree(root.left);
invertTree(root.right);
return root;
};
```
使用迭代版本(统一模板))的前序遍历:
```javascript
var invertTree = function(root) {
//我们先定义节点交换函数
const invertNode=function(root,left,right){
let temp=left;
left=right;
right=temp;
root.left=left;
root.right=right;
}
//使用迭代方法的前序遍历
let stack=[];
if(root===null){
return root;
}
stack.push(root);
while(stack.length){
let node=stack.pop();
if(node!==null){
//前序遍历顺序中左右 入栈顺序是前序遍历的倒序右左中
node.right&&stack.push(node.right);
node.left&&stack.push(node.left);
stack.push(node);
stack.push(null);
}else{
node=stack.pop();
//节点处理逻辑
invertNode(node,node.left,node.right);
}
}
return root;
};
```
使用层序遍历:
```javascript
var invertTree = function(root) {
//我们先定义节点交换函数
const invertNode=function(root,left,right){
let temp=left;
left=right;
right=temp;
root.left=left;
root.right=right;
}
//使用层序遍历
let queue=[];
if(root===null){
return root;
}
queue.push(root);
while(queue.length){
let length=queue.length;
while(length--){
let node=queue.shift();
//节点处理逻辑
invertNode(node,node.left,node.right);
node.left&&queue.push(node.left);
node.right&&queue.push(node.right);
}
}
return root;
};
```
-----------------------
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -247,8 +247,23 @@ class Solution {
```
Python
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root: return root //中
if root.val >p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left,p,q) //左
elif root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right,p,q) //右
else: return root
```
Go
@ -258,4 +273,4 @@ Go
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -263,8 +263,24 @@ class Solution {
```
Python
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
//递归
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or root == p or root == q: return root //找到了节点p或者q或者遇到空节点
left = self.lowestCommonAncestor(root.left,p,q) //左
right = self.lowestCommonAncestor(root.right,p,q) //右
if left and right: return root //中: left和right不为空root就是最近公共节点
elif left and not right: return left //目标节点是通过left返回的
elif not left and right: return right //目标节点是通过right返回的
else: return None //没找到
```
Go
```Go
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {

View File

@ -140,6 +140,29 @@ func isAnagram(s string, t string) bool {
}
```
javaScript:
```js
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
if(s.length !== t.length) return false;
const resSet = new Array(26).fill(0);
const base = "a".charCodeAt();
for(const i of s) {
resSet[i.charCodeAt() - base]++;
}
for(const i of t) {
if(!resSet[i.charCodeAt() - base]) return false;
resSet[i.charCodeAt() - base]--;
}
return true;
};
```
## 相关题目
* 383.赎金信

View File

@ -399,6 +399,49 @@ char ** findItinerary(char *** tickets, int ticketsSize, int* ticketsColSize, in
}
```
Javascript:
```Javascript
var findItinerary = function(tickets) {
let result = ['JFK']
let map = {}
for (const tickt of tickets) {
const [from, to] = tickt
if (!map[from]) {
map[from] = []
}
map[from].push(to)
}
for (const city in map) {
// 对到达城市列表排序
map[city].sort()
}
function backtracing() {
if (result.length === tickets.length + 1) {
return true
}
if (!map[result[result.length - 1]] || !map[result[result.length - 1]].length) {
return false
}
for(let i = 0 ; i < map[result[result.length - 1]].length; i++) {
let city = map[result[result.length - 1]][i]
// 删除已走过航线,防止死循环
map[result[result.length - 1]].splice(i, 1)
result.push(city)
if (backtracing()) {
return true
}
result.pop()
map[result[result.length - 1]].splice(i, 0, city)
}
}
backtracing()
return result
};
```
-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)

View File

@ -122,6 +122,34 @@ Python
Go
javaScript:
```js
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersection = function(nums1, nums2) {
// 根据数组大小交换操作的数组
if(nums1.length < nums2.length) {
const _ = nums1;
nums1 = nums2;
nums2 = _;
}
const nums1Set = new Set(nums1);
const resSet = new Set();
// for(const n of nums2) {
// nums1Set.has(n) && resSet.add(n);
// }
// 循环 比 迭代器快
for(let i = nums2.length - 1; i >= 0; i--) {
nums1Set.has(nums2[i]) && resSet.add(nums2[i]);
}
return Array.from(resSet);
};
```
## 相关题目

View File

@ -136,7 +136,7 @@ class Solution {
```
Python
```
```py
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
@ -167,6 +167,28 @@ class Solution(object):
Go
javaScript:
```js
/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function(ransomNote, magazine) {
const strArr = new Array(26).fill(0),
base = "a".charCodeAt();
for(const s of magazine) {
strArr[s.charCodeAt() - base]++;
}
for(const s of ransomNote) {
const index = s.charCodeAt() - base;
if(!strArr[index]) return false;
strArr[index]--;
}
return true;
};
```

View File

@ -212,7 +212,19 @@ class Solution {
```
Python
```python
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if len(intervals) == 0: return 0
intervals.sort(key=lambda x: x[1])
count = 1 # 记录非交叉区间的个数
end = intervals[0][1] # 记录区间分割点
for i in range(1, len(intervals)):
if end <= intervals[i][0]:
count += 1
end = intervals[i][1]
return len(intervals) - count
```
Go
@ -223,4 +235,4 @@ Go
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -281,7 +281,43 @@ 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 deleteNode(self, root: TreeNode, key: int) -> TreeNode:
if not root: return root #第一种情况:没找到删除的节点,遍历到空节点直接返回了
if root.val == key:
if not root.left and not root.right: #第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
del root
return None
if not root.left and root.right: #第三种情况:其左孩子为空,右孩子不为空,删除节点,右孩子补位 ,返回右孩子为根节点
tmp = root
root = root.right
del tmp
return root
if root.left and not root.right: #第四种情况:其右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
tmp = root
root = root.left
del tmp
return root
else: #第五种情况:左右孩子节点都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子的位置
v = root.right
while v.left:
v = v.left
v.left = root.left
tmp = root
root = root.right
del tmp
return root
if root.val > key: root.left = self.deleteNode(root.left,key) #左递归
if root.val < key: root.right = self.deleteNode(root.right,key) #右递归
return root
```
Go
```Go
@ -330,4 +366,4 @@ func deleteNode1(root *TreeNode)*TreeNode{
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -70,7 +70,7 @@
其实都可以只不过对应的遍历顺序不同我就按照气球的起始位置排序了
既然按照其实位置排序那么就从前向后遍历气球数组靠左尽可能让气球重复
既然按照起始位置排序那么就从前向后遍历气球数组靠左尽可能让气球重复
从前向后遍历遇到重叠的气球了怎么办
@ -167,7 +167,19 @@ class Solution {
```
Python
```python
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
if len(points) == 0: return 0
points.sort(key=lambda x: x[0])
result = 1
for i in range(1, len(points)):
if points[i][0] > points[i - 1][1]: # 气球i和气球i-1不挨着注意这里不是>=
result += 1
else:
points[i][1] = min(points[i - 1][1], points[i][1]) # 更新重叠气球最小右边界
return result
```
Go
@ -178,4 +190,4 @@ Go
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -155,6 +155,38 @@ class Solution(object):
Go
javaScript:
```js
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number[]} nums3
* @param {number[]} nums4
* @return {number}
*/
var fourSumCount = function(nums1, nums2, nums3, nums4) {
const twoSumMap = new Map();
let count = 0;
for(const n1 of nums1) {
for(const n2 of nums2) {
const sum = n1 + n2;
twoSumMap.set(sum, (twoSumMap.get(sum) || 0) + 1)
}
}
for(const n3 of nums3) {
for(const n4 of nums4) {
const sum = n3 + n4;
count += (twoSumMap.get(0 - sum) || 0)
}
}
return count;
};
```

View File

@ -225,7 +225,7 @@ public:
是的如果仅仅是求个数的话就可以用dp但[回溯算法39. 组合总和](https://mp.weixin.qq.com/s/FLg8G6EjVcxBjwCbzpACPw)要求的是把所有组合列出来,还是要使用回溯法爆搜的。
还是有点难度,大家也可以记住,在求装满背包有几种方法的情况下,递推公式一般为:
还是有点难度,大家也可以记住,在求装满背包有几种方法的情况下,递推公式一般为:
```
dp[j] += dp[j - nums[i]];
@ -272,4 +272,4 @@ Go
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -394,8 +394,39 @@ 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 findMode(self, root: TreeNode) -> List[int]:
if not root: return
self.pre = root
self.count = 0 //统计频率
self.countMax = 0 //最大频率
self.res = []
def findNumber(root):
if not root: return None // 第一个节点
findNumber(root.left) //左
if self.pre.val == root.val: //中: 与前一个节点数值相同
self.count += 1
else: // 与前一个节点数值不同
self.pre = root
self.count = 1
if self.count > self.countMax: // 如果计数大于最大值频率
self.countMax = self.count // 更新最大频率
self.res = [root.val] //更新res
elif self.count == self.countMax: // 如果和最大值相同放进res中
self.res.append(root.val)
findNumber(root.right) //右
return
findNumber(root)
return self.res
```
Go
@ -405,4 +436,4 @@ Go
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -207,6 +207,19 @@ class Solution:
```
Go
```Go
func fib(n int) int {
if n < 2 {
return n
}
a, b, c := 0, 1, 0
for i := 1; i < n; i++ {
c = a + b
a, b = b, c
}
return c
}
```

View File

@ -196,8 +196,26 @@ class Solution {
```
Python
```python3
# 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 convertBST(self, root: TreeNode) -> TreeNode:
def buildalist(root):
if not root: return None
buildalist(root.right) #右中左遍历
root.val += self.pre
self.pre = root.val
buildalist(root.left)
self.pre = 0 #记录前一个节点的数值
buildalist(root)
return root
```
Go
@ -207,4 +225,4 @@ Go
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -134,6 +134,36 @@ class Solution {
```
Python
```python
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
from functools import reduce
# turn s into a list
s = list(s)
# another way to simply use a[::-1], but i feel this is easier to understand
def reverse(s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return s
# make sure we reverse each 2k elements
for i in range(0, len(s), 2*k):
s[i:(i+k)] = reverse(s[i:(i+k)])
# combine list into str.
return reduce(lambda a, b: a+b, s)
```
Go

View File

@ -265,8 +265,24 @@ class Solution {
```
Python
```python3
# 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 trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
if not root: return root
if root.val < low:
return self.trimBST(root.right,low,high) // 寻找符合区间[low, high]的节点
if root.val > high:
return self.trimBST(root.left,low,high) // 寻找符合区间[low, high]的节点
root.left = self.trimBST(root.left,low,high) // root->left接入符合条件的左孩子
root.right = self.trimBST(root.right,low,high) // root->right接入符合条件的右孩子
return root
```
Go
@ -276,4 +292,4 @@ Go
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -254,6 +254,43 @@ func search(nums []int, target int) int {
}
```
javaScript
```js
// (版本一)左闭右闭区间
var search = function(nums, target) {
let l = 0, r = nums.length - 1;
// 区间 [l, r]
while(l <= r) {
let mid = (l + r) >> 1;
if(nums[mid] === target) return mid;
let isSmall = nums[mid] < target;
l = isSmall ? mid + 1 : l;
r = isSmall ? r : mid - 1;
}
return -1;
};
// (版本二)左闭右开区间
var search = function(nums, target) {
let l = 0, r = nums.length;
// 区间 [l, r
while(l < r) {
let mid = (l + r) >> 1;
if(nums[mid] === target) return mid;
let isSmall = nums[mid] < target;
l = isSmall ? mid + 1 : l;
// 所以 mid 不会被取到
r = isSmall ? r : mid;
}
return -1;
};
```

View File

@ -393,6 +393,142 @@ class MyLinkedList:
Go
javaScript:
```js
class LinkNode {
constructor(val, next) {
this.val = val;
this.next = next;
}
}
/**
* Initialize your data structure here.
* 单链表 储存头尾节点 和 节点数量
*/
var MyLinkedList = function() {
this._size = 0;
this._tail = null;
this._head = null;
};
/**
* Get the value of the index-th node in the linked list. If the index is invalid, return -1.
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.getNode = function(index) {
if(index < 0 || index >= this._size) return null;
// 创建虚拟头节点
let cur = new LinkNode(0, this._head);
// 0 -> head
while(index-- >= 0) {
cur = cur.next;
}
return cur;
};
MyLinkedList.prototype.get = function(index) {
if(index < 0 || index >= this._size) return -1;
// 获取当前节点
return this.getNode(index).val;
};
/**
* Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function(val) {
const node = new LinkNode(val, this._head);
this._head = node;
this._size++;
if(!this._tail) {
this._tail = node;
}
};
/**
* Append a node of value val to the last element of the linked list.
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function(val) {
const node = new LinkNode(val, null);
this._size++;
if(this._tail) {
this._tail.next = node;
this._tail = node;
return;
}
this._tail = node;
this._head = node;
};
/**
* Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function(index, val) {
if(index > this._size) return;
if(index <= 0) {
this.addAtHead(val);
return;
}
if(index === this._size) {
this.addAtTail(val);
return;
}
// 获取目标节点的上一个的节点
const node = this.getNode(index - 1);
node.next = new LinkNode(val, node.next);
this._size++;
};
/**
* Delete the index-th node in the linked list, if the index is valid.
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function(index) {
if(index < 0 || index >= this._size) return;
if(index === 0) {
this._head = this._head.next;
this._size--;
return;
}
// 获取目标节点的上一个的节点
const node = this.getNode(index - 1);
node.next = node.next.next;
// 处理尾节点
if(index === this._size - 1) {
this._tail = node;
}
this._size--;
};
// MyLinkedList.prototype.out = function() {
// let cur = this._head;
// const res = [];
// while(cur) {
// res.push(cur.val);
// cur = cur.next;
// }
// };
/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = new MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/
```

View File

@ -199,7 +199,21 @@ class Solution { // 动态规划
Python
```python
class Solution: # 贪心思路
def maxProfit(self, prices: List[int], fee: int) -> int:
result = 0
minPrice = prices[0]
for i in range(1, len(prices)):
if prices[i] < minPrice:
minPrice = prices[i]
elif prices[i] >= minPrice and prices[i] <= minPrice + fee:
continue
else:
result += prices[i] - minPrice - fee
minPrice = prices[i] - fee
return result
```
Go

View File

@ -8,6 +8,7 @@
## 738.单调递增的数字
题目链接: https://leetcode-cn.com/problems/monotone-increasing-digits/
给定一个非负整数 N找出小于或等于 N 的最大的整数同时这个整数需要满足其各个位数上的数字是单调递增。
@ -30,7 +31,7 @@
## 暴力解法
题意很简单,那么首先想的就是暴力解法了,来我大家暴力一波,结果自然是超时!
题意很简单,那么首先想的就是暴力解法了,来我大家暴力一波,结果自然是超时!
代码如下:
```C++
@ -146,7 +147,19 @@ class Solution {
Python
```python
class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
strNum = list(str(n))
flag = len(strNum)
for i in range(len(strNum) - 1, 0, -1):
if int(strNum[i]) < int(strNum[i - 1]):
strNum[i - 1] = str(int(strNum[i - 1]) - 1)
flag = i
for i in range(flag, len(strNum)):
strNum[i] = '9'
return int("".join(strNum))
```
Go
@ -157,4 +170,4 @@ Go
* 作者微信:[程序员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>
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

View File

@ -228,7 +228,23 @@ Python
Go
```Go
func minCostClimbingStairs(cost []int) int {
dp := make([]int, len(cost))
dp[0], dp[1] = cost[0], cost[1]
for i := 2; i < len(cost); i++ {
dp[i] = min(dp[i-1], dp[i-2]) + cost[i]
}
return min(dp[len(cost)-1], dp[len(cost)-2])
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
```

View File

@ -108,7 +108,23 @@ class Solution {
```
Python
```python
class Solution:
def partitionLabels(self, s: str) -> List[int]:
hash = [0] * 26
for i in range(len(s)):
hash[ord(s[i]) - ord('a')] = i
result = []
left = 0
right = 0
for i in range(len(s)):
right = max(right, hash[ord(s[i]) - ord('a')])
if i == right:
result.append(right - left + 1)
left = i + 1
return result
```
Go

View File

@ -122,6 +122,8 @@ public:
Java
使用 Deque 作为堆栈
```Java
class Solution {
public String removeDuplicates(String S) {
@ -144,6 +146,30 @@ class Solution {
}
}
```
拿字符串直接作为栈,省去了栈还要转为字符串的操作。
```Java
class Solution {
public String removeDuplicates(String s) {
// 将 res 当做栈
StringBuffer res = new StringBuffer();
// top为 res 的长度
int top = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// 当 top > 0,即栈中有字符时,当前字符如果和栈中字符相等,弹出栈顶字符,同时 top--
if (top >= 0 && res.charAt(top) == c) {
res.deleteCharAt(top);
top--;
// 否则,将该字符 入栈同时top++
} else {
res.append(c);
top++;
}
}
return res.toString();
}
}
```
Python
```python3

View File

@ -242,7 +242,137 @@ Python
Go
> 前序遍历统一迭代法
```GO
/**
type Element struct {
// 元素保管的值
Value interface{}
// 内含隐藏或非导出字段
}
func (l *List) Back() *Element
前序遍历:中左右
压栈顺序:右左中
**/
func preorderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
var stack = list.New()//栈
res:=[]int{}//结果集
stack.PushBack(root)
var node *TreeNode
for stack.Len()>0{
e := stack.Back()
stack.Remove(e)//弹出元素
if e.Value==nil{// 如果为空,则表明是需要处理中间节点
e=stack.Back()//弹出元素(即中间节点)
stack.Remove(e)//删除中间节点
node=e.Value.(*TreeNode)
res=append(res,node.Val)//将中间节点加入到结果集中
continue//继续弹出栈中下一个节点
}
node = e.Value.(*TreeNode)
//压栈顺序:右左中
if node.Right!=nil{
stack.PushBack(node.Right)
}
if node.Left!=nil{
stack.PushBack(node.Left)
}
stack.PushBack(node)//中间节点压栈后再压入nil作为中间节点的标志符
stack.PushBack(nil)
}
return res
}
```
> 中序遍历统一迭代法
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
//中序遍历:左中右
//压栈顺序:右中左
func inorderTraversal(root *TreeNode) []int {
if root==nil{
return nil
}
stack:=list.New()//栈
res:=[]int{}//结果集
stack.PushBack(root)
var node *TreeNode
for stack.Len()>0{
e := stack.Back()
stack.Remove(e)
if e.Value==nil{// 如果为空,则表明是需要处理中间节点
e=stack.Back()//弹出元素(即中间节点)
stack.Remove(e)//删除中间节点
node=e.Value.(*TreeNode)
res=append(res,node.Val)//将中间节点加入到结果集中
continue//继续弹出栈中下一个节点
}
node = e.Value.(*TreeNode)
//压栈顺序:右中左
if node.Right!=nil{
stack.PushBack(node.Right)
}
stack.PushBack(node)//中间节点压栈后再压入nil作为中间节点的标志符
stack.PushBack(nil)
if node.Left!=nil{
stack.PushBack(node.Left)
}
}
return res
}
```
> 后序遍历统一迭代法
```go
//后续遍历:左右中
//压栈顺序:中右左
func postorderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
var stack = list.New()//栈
res:=[]int{}//结果集
stack.PushBack(root)
var node *TreeNode
for stack.Len()>0{
e := stack.Back()
stack.Remove(e)
if e.Value==nil{// 如果为空,则表明是需要处理中间节点
e=stack.Back()//弹出元素(即中间节点)
stack.Remove(e)//删除中间节点
node=e.Value.(*TreeNode)
res=append(res,node.Val)//将中间节点加入到结果集中
continue//继续弹出栈中下一个节点
}
node = e.Value.(*TreeNode)
//压栈顺序:中右左
stack.PushBack(node)//中间节点压栈后再压入nil作为中间节点的标志符
stack.PushBack(nil)
if node.Right!=nil{
stack.PushBack(node.Right)
}
if node.Left!=nil{
stack.PushBack(node.Left)
}
}
return res
}
```

View File

@ -306,6 +306,59 @@ var postorderTraversal = function(root, res = []) {
return res;
};
```
Javascript版本
前序遍历:
```Javascript
var preorderTraversal = function(root) {
let res=[];
const dfs=function(root){
if(root===null)return ;
//先序遍历所以从父节点开始
res.push(root.val);
//递归左子树
dfs(root.left);
//递归右子树
dfs(root.right);
}
//只使用一个参数 使用闭包进行存储结果
dfs(root);
return res;
};
```
中序遍历
```javascript
var inorderTraversal = function(root) {
let res=[];
const dfs=function(root){
if(root===null){
return ;
}
dfs(root.left);
res.push(root.val);
dfs(root.right);
}
dfs(root);
return res;
};
```
后序遍历
```javascript
var postorderTraversal = function(root) {
let res=[];
const dfs=function(root){
if(root===null){
return ;
}
dfs(root.left);
dfs(root.right);
res.push(root.val);
}
dfs(root);
return res;
};
```

View File

@ -96,10 +96,27 @@ public:
## 其他语言版本
Java
```java
class Solution {
public String reverseLeftWords(String s, int n) {
int len=s.length();
StringBuilder sb=new StringBuilder(s);
reverseString(sb,0,n-1);
reverseString(sb,n,len-1);
return sb.reverse().toString();
}
public void reverseString(StringBuilder sb, int start, int end) {
while (start < end) {
char temp = sb.charAt(start);
sb.setCharAt(start, sb.charAt(end));
sb.setCharAt(end, temp);
start++;
end--;
}
}
}
```
Python

View File

@ -155,6 +155,42 @@ Python
Go
javaScript:
```js
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getListLen = function(head) {
let len = 0, cur = head;
while(cur) {
len++;
cur = cur.next;
}
return len;
}
var getIntersectionNode = function(headA, headB) {
let curA = headA,curB = headB,
lenA = getListLen(headA),
lenB = getListLen(headB);
if(lenA < lenB) {
[curA, curB] = [curB, curA];
[lenA, lenB] = [lenB, lenA];
}
let i = lenA - lenB;
while(i-- > 0) {
curA = curA.next
}
while(curA && curA !== curB) {
curA = curA.next;
curB = curB.next;
}
return curA;
};
```