Merge branch 'master' into patch-1

This commit is contained in:
Carl Sun
2021-05-14 09:36:49 +08:00
committed by GitHub
56 changed files with 1653 additions and 180 deletions

View File

@ -123,6 +123,22 @@ public:
Java
```java
class Solution {
public int removeElement(int[] nums, int val) {
int p2 = 0;
for (int p1 = 0; p1 < nums.length; p1++) {
if (nums[p1] != val) {
nums[p2] = nums[p1];
p2++;
}
}
return p2;
}
}
```
Python
@ -172,4 +188,4 @@ var removeElement = (nums, val) => {
* 作者微信:[程序员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

@ -137,7 +137,35 @@ public:
Java
```java
class Solution {
public int[][] merge(int[][] intervals) {
List<int[]> res = new LinkedList<>();
Arrays.sort(intervals, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] != o2[0]) {
return Integer.compare(o1[0],o2[0]);
} else {
return Integer.compare(o1[1],o2[1]);
}
}
});
int start = intervals[0][0];
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] > intervals[i - 1][1]) {
res.add(new int[]{start, intervals[i - 1][1]});
start = intervals[i][0];
} else {
intervals[i][1] = Math.max(intervals[i][1], intervals[i - 1][1]);
}
}
res.add(new int[]{start, intervals[intervals.length - 1][1]});
return res.toArray(new int[res.size()][]);
}
}
```
Python
@ -151,4 +179,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

@ -127,7 +127,23 @@ public:
Java
```java
class Solution {
public int climbStairs(int n) {
int[] dp = new int[n + 1];
int[] weight = {1,2};
dp[0] = 1;
for (int i = 0; i <= n; i++) {
for (int j = 0; j < weight.length; j++) {
if (i >= weight[j]) dp[i] += dp[i - weight[j]];
}
}
return dp[n];
}
}
```
Python
@ -141,4 +157,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,19 @@ public:
Java
```java
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST_2(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValidBST_2 (TreeNode root, long lo, long hi) {
if (root == null) return true;
if (root.val >= hi || root.val <= lo) return false;
return isValidBST_2(root.left,lo,root.val) && isValidBST_2(root.right,root.val,hi);
}
}
```
Python
@ -286,4 +299,4 @@ func isBST(root *TreeNode, min, max int) bool {
* 作者微信:[程序员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,7 +254,94 @@ public:
## 其他语言版本
Java
```java
public class N0101 {
/**
* 解法1DFS递归。
*/
public boolean isSymmetric2(TreeNode root) {
if (root == null) {
return false;
}
return compare(root.left, root.right);
}
private boolean compare(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left != null && right == null) {
return false;
}
if (left == null && right != null) {
return false;
}
if (left.val == right.val) {
return compare(left.left, right.right) && compare(left.right, right.left);
}
return false;
}
/**
* 解法2DFS迭代
*/
public boolean isSymmetric3(TreeNode root) {
if (root == null) {
return false;
}
if (!equal(root.left, root.right)) {
return false;
}
Deque<TreeNode> st = new LinkedList<>();
st.push(root.right);
st.push(root.left);
TreeNode curR = root.right;
TreeNode curL = root.left;
while (!st.isEmpty()) {
curL = st.pop();
curR = st.pop();
// 前序,处理
if (!equal(curL, curR)) {
return false;
}
if (curR != null && curL != null) {
st.push(curL.right);
st.push(curR.left);
st.push(curR.right);
st.push(curL.left);
}
}
return true;
}
private boolean equal(TreeNode l, TreeNode r) {
if (l == null && r == null) {
return true;
}
if (l != null && r == null) {
return false;
}
if (l == null && r != null) {
return false;
}
if (l.val == r.val) {
return true;
}
return false;
}
}
```
Python
@ -283,4 +370,4 @@ const check = (leftPtr, rightPtr) => {
* 作者微信:[程序员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

@ -420,54 +420,236 @@ public:
Java
```Java
// 102.二叉树的层序遍历
class Solution {
public List<List<Integer>> resList=new ArrayList<List<Integer>>();
public List<List<Integer>> resList = new ArrayList<List<Integer>>();
public List<List<Integer>> levelOrder(TreeNode root) {
//checkFun01(root,0);
checkFun02(root);
return resList;
}
//DFS--递归方式
public void checkFun01(TreeNode node,Integer deep){
if(node==null) return;
//DFS--递归方式
public void checkFun01(TreeNode node, Integer deep) {
if (node == null) return;
deep++;
if(resList.size()<deep){
if (resList.size() < deep) {
//当层级增加时list的Item也增加利用list的索引值进行层级界定
List<Integer> item=new ArrayList<Integer>();
List<Integer> item = new ArrayList<Integer>();
resList.add(item);
}
resList.get(deep-1).add(node.val);
checkFun01(node.left,deep);
checkFun01(node.right,deep);
resList.get(deep - 1).add(node.val);
checkFun01(node.left, deep);
checkFun01(node.right, deep);
}
//BFS--迭代方式--借助队列
public void checkFun02(TreeNode node){
if(node==null) return;
Queue<TreeNode> que=new LinkedList<TreeNode>();
public void checkFun02(TreeNode node) {
if (node == null) return;
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.offer(node);
while(!que.isEmpty()){
List<Integer> itemList=new ArrayList<Integer>();
int len=que.size();
while (!que.isEmpty()) {
List<Integer> itemList = new ArrayList<Integer>();
int len = que.size();
while(len>0){
TreeNode tmpNode=que.poll();
while (len > 0) {
TreeNode tmpNode = que.poll();
itemList.add(tmpNode.val);
if(tmpNode.left!=null) que.offer(tmpNode.left);
if(tmpNode.right!=null) que.offer(tmpNode.right);
if (tmpNode.left != null) que.offer(tmpNode.left);
if (tmpNode.right != null) que.offer(tmpNode.right);
len--;
}
resList.add(itemList);
}
}
}
// 107. 二叉树的层序遍历 II
public class N0107 {
/**
* 解法:队列,迭代。
* 层序遍历,再翻转数组即可。
*/
public List<List<Integer>> solution1(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
Deque<TreeNode> que = new LinkedList<>();
if (root == null) {
return list;
}
que.offerLast(root);
while (!que.isEmpty()) {
List<Integer> levelList = new ArrayList<>();
int levelSize = que.size();
for (int i = 0; i < levelSize; i++) {
TreeNode peek = que.peekFirst();
levelList.add(que.pollFirst().val);
if (peek.left != null) {
que.offerLast(peek.left);
}
if (peek.right != null) {
que.offerLast(peek.right);
}
}
list.add(levelList);
}
List<List<Integer>> result = new ArrayList<>();
for (int i = list.size() - 1; i >= 0; i-- ) {
result.add(list.get(i));
}
return result;
}
}
// 199.二叉树的右视图
public class N0199 {
/**
* 解法:队列,迭代。
* 每次返回每层的最后一个字段即可。
*
* 小优化:每层右孩子先入队。代码略。
*/
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> que = new LinkedList<>();
if (root == null) {
return list;
}
que.offerLast(root);
while (!que.isEmpty()) {
int levelSize = que.size();
for (int i = 0; i < levelSize; i++) {
TreeNode poll = que.pollFirst();
if (poll.left != null) {
que.addLast(poll.left);
}
if (poll.right != null) {
que.addLast(poll.right);
}
if (i == levelSize - 1) {
list.add(poll.val);
}
}
}
return list;
}
}
// 637. 二叉树的层平均值
public class N0637 {
/**
* 解法:队列,迭代。
* 每次返回每层的最后一个字段即可。
*/
public List<Double> averageOfLevels(TreeNode root) {
List<Double> list = new ArrayList<>();
Deque<TreeNode> que = new LinkedList<>();
if (root == null) {
return list;
}
que.offerLast(root);
while (!que.isEmpty()) {
TreeNode peek = que.peekFirst();
int levelSize = que.size();
double levelSum = 0.0;
for (int i = 0; i < levelSize; i++) {
TreeNode poll = que.pollFirst();
levelSum += poll.val;
if (poll.left != null) {
que.addLast(poll.left);
}
if (poll.right != null) {
que.addLast(poll.right);
}
}
list.add(levelSum / levelSize);
}
return list;
}
}
// 429. N 叉树的层序遍历
public class N0429 {
/**
* 解法1队列迭代。
*/
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> list = new ArrayList<>();
Deque<Node> que = new LinkedList<>();
if (root == null) {
return list;
}
que.offerLast(root);
while (!que.isEmpty()) {
int levelSize = que.size();
List<Integer> levelList = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
Node poll = que.pollFirst();
levelList.add(poll.val);
List<Node> children = poll.children;
if (children == null || children.size() == 0) {
continue;
}
for (Node child : children) {
if (child != null) {
que.offerLast(child);
}
}
}
list.add(levelList);
}
return list;
}
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
}
}
```

View File

@ -231,6 +231,18 @@ public:
Java
```java
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftdeep = maxDepth(root.left);
int rightdeep = maxDepth(root.right);
return 1+Math.max(leftdeep,rightdeep);
}
}
```
Python
@ -239,10 +251,16 @@ Python
Go
JavaScript
```javascript
var maxDepth = function(root) {
if (!root) return root
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right))
};
```
-----------------------
* 作者微信:[程序员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

@ -582,6 +582,47 @@ tree2 的前序遍历是[1 2 3] 后序遍历是[3 2 1]。
Java
```java
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder.length == 0 || postorder.length == 0) return null;
return buildTree(inorder, postorder,0,inorder.length,0,postorder.length);
}
private TreeNode buildTree(int[] inorder, int[] postorder, int infrom, int into,
int postfrom, int postto) {
if (postfrom == postto) return null;
int rootValue = postorder[postto - 1];
TreeNode root = new TreeNode(rootValue);
if (postfrom + 1 == postto) return root;
int splitNum = postto - 1;
for (int i = infrom; i < into; i++) {
if (inorder[i] == rootValue) {
splitNum = i;
break;
}
}
int inLeftBegin = infrom;
int inLeftEnd = splitNum;
int inRightBegin = splitNum + 1;
int inRightEnd = into;
int postLeftBegin = postfrom;
int postLeftEnd = postLeftBegin + (splitNum - inLeftBegin);
int postRightBegin = postLeftBegin + (splitNum - inLeftBegin);
int postRightEnd = postto - 1;
root.left = buildTree(inorder,postorder,inLeftBegin,inLeftEnd,postLeftBegin,postLeftEnd);
root.right = buildTree(inorder,postorder,inRightBegin,inRightEnd,postRightBegin,postRightEnd);
return root;
}
}
```
Python
@ -596,4 +637,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

@ -209,6 +209,26 @@ public:
Java
```java
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return sortArr(nums,0,nums.length);
}
private TreeNode sortArr(int[] nums, int lo, int hi) {
if (lo == hi) return null;
int rootIdx = (lo + hi)/2;
int rootValue = nums[rootIdx];
TreeNode root = new TreeNode(rootValue);
root.left = sortArr(nums,lo,rootIdx);
root.right = sortArr(nums,rootIdx+1,hi);
return root;
}
}
```
Python
@ -223,4 +243,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

@ -354,6 +354,29 @@ public:
## 其他语言版本
Java
```java
class Solution {
boolean flag = true;
public boolean isBalanced(TreeNode root) {
high(root);
return flag;
}
private int high (TreeNode root) {
if (root == null) return 0;
if (flag) {
int left = high(root.left);
int right = high(root.right);
if (Math.abs(left - right) > 1) flag = false;
return Math.max(left,right) + 1;
} else {
return -1;
}
}
}
```
Python

View File

@ -194,6 +194,20 @@ public:
Java
```java
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
int leftDeep = minDepth(root.left);
int rightDeep = minDepth(root.right);
if (root.left == null && root.right != null) return 1+rightDeep;
if (root.left != null && root.right == null) return 1+leftDeep;
return Math.min(leftDeep,rightDeep)+1;
}
}
```
Python

View File

@ -305,6 +305,24 @@ public:
Java
```java
class Solution {
private boolean flag = false;
public boolean hasPathSum(TreeNode root, int targetSum) {
has_2(root,targetSum);
return flag;
}
public void has_2 (TreeNode root, int count) {
if (root == null) return;
if (root.left == null && root.right == null && count == root.val) {
flag = true;
}
if (root.left != null) has_2(root.left,count - root.val);
if (root.right != null) has_2(root.right,count - root.val);
}
}
```
Python
@ -387,4 +405,4 @@ let pathSum = function (root, targetSum) {
* 作者微信:[程序员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

@ -135,7 +135,23 @@ public:
Java
```java
class Solution {
public int maxProfit(int[] prices) {
int sum = 0;
int profit = 0;
int buy = prices[0];
for (int i = 1; i < prices.length; i++) {
profit = prices[i] - buy;
if (profit > 0) {
sum += profit;
}
buy = prices[i];
}
return sum;
}
}
```
Python
@ -149,4 +165,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

@ -199,7 +199,28 @@ public:
Java
```java
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int sum = 0;
int min = 0;
for (int i = 0; i < gas.length; i++) {
sum += (gas[i] - cost[i]);
min = Math.min(sum, min);
}
if (sum < 0) return -1;
if (min >= 0) return 0;
for (int i = gas.length - 1; i > 0; i--) {
min += (gas[i] - cost[i]);
if (min >= 0) return i;
}
return -1;
}
}
```
Python
@ -213,4 +234,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

@ -130,7 +130,35 @@ public:
Java
```java
class Solution {
public int candy(int[] ratings) {
int[] candy = new int[ratings.length];
for (int i = 0; i < candy.length; i++) {
candy[i] = 1;
}
for (int i = 1; i < ratings.length; i++) {
if (ratings[i] > ratings[i - 1]) {
candy[i] = candy[i - 1] + 1;
}
}
for (int i = ratings.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candy[i] = Math.max(candy[i],candy[i + 1] + 1);
}
}
int count = 0;
for (int i = 0; i < candy.length; i++) {
count += candy[i];
}
return count;
}
}
```
Python
@ -144,4 +172,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

@ -232,7 +232,23 @@ public:
Java
```java
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] valid = new boolean[s.length() + 1];
valid[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (wordDict.contains(s.substring(j,i)) && valid[j]) {
valid[i] = true;
}
}
}
return valid[s.length()];
}
}
```
Python
@ -246,4 +262,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

@ -186,7 +186,35 @@ public:
Java
```java
public class Solution {
public ListNode detectCycle(ListNode head) {
// 1.寻找相遇点
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast != slow) {
continue;
}
ListNode meet = fast;
// 2.寻找入口点
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
return null;
}
}
```
Python

View File

@ -212,6 +212,77 @@ public:
Java
```java
class Solution {
public String reverseWords(String s) {
char[] chars = s.toCharArray();
// 1.双指针去除空格
// 去除头尾空格
int head = 0;
while (chars[head] == ' ') {
head ++;
}
int tail = chars.length - 1;
while (chars[tail] == ' ') {
tail --;
}
// 去除中间空格
int p1 = head;
int p2 = head + 1;
while (p2 <= tail) {
if (chars[p2 -1] == ' ' && chars[p2] == ' ') {
p2 ++;
continue;
}
chars[p1 + 1] = chars[p2];
p1 ++;
p2 ++;
}
tail = p1;
// 2.双指针翻转整个字符串
chars = reverse(chars, head, tail);
// 3.双指针翻转每个单词
p1 = head;
p2 = head;
for (int i = head; i <= tail;) {
int add = 0;
while (i + add <= tail && chars[i + add] != ' ') {
add ++;
}
if (i + add != tail) {
reverse(chars, i, i + add - 1);
i += add + 1;
} else {
reverse(chars, i, tail);
i = tail + 1;
}
}
return new String(chars, head, tail - head + 1);
}
char[] reverse(char[] chars, int begin, int end) {
int p1 = begin;
int p2 = end;
while (p1 < p2) {
chars[p1] ^= chars[p2];
chars[p2] ^= chars[p1];
chars[p1] ^= chars[p2];
p1 ++;
p2 --;
}
return chars;
}
}
```
Python

View File

@ -102,6 +102,24 @@ public:
Java
```java
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode last = head;
ListNode cur = head.next;
head.next = null;
while (cur.next != null) {
ListNode tmp = cur.next;
cur.next = last;
last = cur;
cur = tmp;
}
cur.next = last;
return cur;
}
}
```
Python
@ -116,4 +134,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

@ -150,6 +150,7 @@ class Solution:
Java
```java
class Solution {
// 滑动窗口
public int minSubArrayLen(int s, int[] nums) {
int left = 0;
@ -194,4 +195,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

@ -227,7 +227,30 @@ public:
Java
```java
class Solution {
private List<Integer> path = new ArrayList<>();
private List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtracking(k, n, 1);
return res;
}
private void backtracking (int k, int count, int start) {
if (count == 0 && k == 0) {
res.add(new ArrayList<>(path));
return;
}
for (int i = start; i <= 9; i++) {
path.add(i);
backtracking(k - 1, count - i, i + 1);
path.remove(path.size() - 1);
}
}
}
```
Python
@ -241,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

@ -194,7 +194,18 @@ public:
Java
```java
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
int leftnum = countNodes(root.left);
int rightnum = countNodes(root.right);
return leftnum + rightnum + 1;
}
}
```
Python
@ -208,4 +219,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

@ -203,7 +203,25 @@ public:
Java
```java
class Solution {
public TreeNode invertTree(TreeNode root) {
invert(root);
return root;
}
private static void invert (TreeNode root) {
if (root == null) return;
invert(root.left);
TreeNode t = root.left;
root.left = root.right;
root.right = t;
invert(root.left);
}
}
```
Python
@ -230,4 +248,4 @@ func invertTree(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

@ -29,7 +29,7 @@
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
输出: 2
解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
 
说明:
@ -229,7 +229,22 @@ public:
Java
```java
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (true) {
if (root.val > p.val && root.val > q.val) {
root = root.left;
} else if (root.val < p.val && root.val < q.val) {
root = root.right;
} else {
break;
}
}
return root;
}
}
```
Python
@ -243,4 +258,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

@ -223,7 +223,20 @@ public:
Java
```java
class Solution {
TreeNode pre;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root.val == p.val ||root.val == q.val) return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if (left != null && right != null) return root;
else if (left == null && right != null) return right;
else if (left != null && right == null) return left;
else return null;
}
}
```
Python
@ -237,4 +250,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

@ -88,6 +88,7 @@ Java
```java
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
for (char c : s.toCharArray()) {
record[c - 'a'] += 1;
@ -138,4 +139,4 @@ func isAnagram(s string, t string) bool {
* 作者微信:[程序员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

@ -280,8 +280,39 @@ public:
## 其他语言版本
Java
```java
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
List<String> list = new LinkedList<>();
TreePaths(root,stack,list);
return list;
}
private static void TreePaths (TreeNode root, LinkedList<TreeNode> path, List<String> res) {
path.add(root);
if (root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (TreeNode n : path) {
sb.append(n.val);
sb.append("->");
}
sb.delete(sb.length()-2,sb.length());
res.add(sb.toString());
return;
}
if (root.left != null) {
TreePaths(root.left, path, res);
path.removeLast();
}
if (root.right != null) {
TreePaths(root.right, path, res);
path.removeLast();
}
}
}
```
Python
@ -296,4 +327,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

@ -133,7 +133,59 @@ public:
Java
```java
public class N0347 {
/**
* 解法:
* 1.统计频次。O(n)
* 2.排序。O(nlogn)
* 3.取前K个元素
*
* 注意到排序的时候需要用小顶堆而不是大顶堆。因为每次需要把最小的堆顶弹出去最后才剩下最大的k个。
* 时间复杂度O(n + nlogk) = O(nlogk)
*/
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = statistic(nums);
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return map.get(o1) - map.get(o2);
}
});
for (Integer key : map.keySet()) {
if (pq.size() < k) {
pq.offer(key);
} else if (map.get(pq.peek()) < map.get(key)){
pq.poll();
pq.offer(key);
}
}
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = pq.poll();
}
return result;
}
// key: 值value次数
private HashMap<Integer, Integer> statistic(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (map.get(num) == null) {
map.put(num, 1);
} else {
map.put(num, map.get(num) + 1);
}
}
return map;
}
}
```
Python

View File

@ -147,6 +147,7 @@ C++测试用例有超过两个树相加超过int的数据所以需要在if里
Java
```Java
class Solution {
public int combinationSum4(int[] nums, int target) {
@ -163,10 +164,23 @@ class Solution {
}
}
```
Python
```python
class Solution:
def combinationSum4(self, nums, target):
dp = [0] * (target + 1)
dp[0] = 1
for i in range(1, target+1):
for j in nums:
if i >= j:
dp[i] += dp[i - j]
return dp[-1]
```
Go
@ -177,4 +191,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

@ -204,7 +204,6 @@ class Solution {
Python
@ -217,5 +216,6 @@ 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>

View File

@ -185,7 +185,30 @@ public:
Java
```java
class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] != o2[0]) {
return Integer.compare(o2[0],o1[0]);
} else {
return Integer.compare(o1[1],o2[1]);
}
}
});
LinkedList<int[]> que = new LinkedList<>();
for (int[] p : people) {
que.add(p[1],p);
}
return que.toArray(new int[people.length][]);
}
}
```
Python
@ -199,4 +222,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

@ -182,7 +182,34 @@ public:
Java
```java
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
if (intervals.length < 2) return 0;
Arrays.sort(intervals, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] != o2[0]) {
return Integer.compare(o1[1],o2[1]);
} else {
return Integer.compare(o2[0],o1[0]);
}
}
});
int count = 0;
int edge = intervals[0][1];
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < edge) {
count++;
} else {
edge = intervals[i][1];
}
}
return count;
}
}
```
Python
@ -196,4 +223,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

@ -251,7 +251,34 @@ public:
Java
```java
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
root = delete(root,key);
return root;
}
private TreeNode delete(TreeNode root, int key) {
if (root == null) return null;
if (root.val > key) {
root.left = delete(root.left,key);
} else if (root.val < key) {
root.right = delete(root.right,key);
} else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
TreeNode tmp = root.right;
while (tmp.left != null) {
tmp = tmp.left;
}
root.val = tmp.val;
root.right = delete(root.right,tmp.val);
}
return root;
}
}
```
Python
@ -303,4 +330,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

@ -139,7 +139,32 @@ public:
Java
```java
class Solution {
public int findMinArrowShots(int[][] points) {
Arrays.sort(points, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] != o2[0]) {
return Integer.compare(o1[0],o2[0]);
} else {
return Integer.compare(o1[0],o2[0]);
}
}
});
int count = 1;
for (int i = 1; i < points.length; i++) {
if (points[i][0] > points[i - 1][1]) {
count++;
} else {
points[i][1] = Math.min(points[i][1],points[i - 1][1]);
}
}
return count;
}
}
```
Python
@ -153,4 +178,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

@ -30,7 +30,7 @@
你有两个孩子和三块小饼干2个孩子的胃口值分别是1,2。
你拥有的饼干数量和尺寸都足以让所有孩子满足。
所以你应该输出2.
 
提示:
* 1 <= g.length <= 3 * 10^4
@ -115,7 +115,23 @@ public:
Java
```java
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int start = 0;
int count = 0;
for (int i = 0; i < s.length && start < g.length; i++) {
if (s[i] >= g[start]) {
start++;
count++;
}
}
return count;
}
}
```
Python
@ -129,4 +145,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

@ -200,6 +200,32 @@ public:
Java
```java
class Solution {
private List<Integer> path = new ArrayList<>();
private List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums,0);
return res;
}
private void backtracking (int[] nums, int start) {
if (path.size() > 1) {
res.add(new ArrayList<>(path));
}
int[] used = new int[201];
for (int i = start; i < nums.length; i++) {
if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) ||
(used[nums[i] + 100] == 1)) continue;
used[nums[i] + 100] = 1;
path.add(nums[i]);
backtracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}
```
Python
@ -214,4 +240,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

@ -241,7 +241,24 @@ dp[j] += dp[j - nums[i]];
Java
```java
class Solution {
public int findTargetSumWays(int[] nums, int target) {
int sum = 0;
for (int i = 0; i < nums.length; i++) sum += nums[i];
if ((target + sum) % 2 != 0) return 0;
int size = (target + sum) / 2;
int[] dp = new int[size + 1];
dp[0] = 1;
for (int i = 0; i < nums.length; i++) {
for (int j = size; j >= nums[i]; j--) {
dp[j] += dp[j - nums[i]];
}
}
return dp[size];
}
}
```
Python
@ -255,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

@ -344,7 +344,47 @@ public:
Java
```java
class Solution {
private LinkedList<Integer> list = new LinkedList<>();
private int currentValue;
private int count;
private int maxCount;
public int[] findMode(TreeNode root) {
count = 0;
maxCount = 0;
currentValue = root.val;
findModeTrl(root);
int[] res = new int[list.size()];
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
return res;
}
private void findModeTrl (TreeNode root) {
if (root == null) return;
findModeTrl(root.left);
if (root.val == currentValue) {
count++;
} else {
currentValue = root.val;
count = 1;
}
if (count == maxCount) {
list.add(root.val);
} else if (count > maxCount) {
maxCount = count;
list.clear();
list.add(currentValue);
}
findModeTrl(root.right);
}
}
```
Python
@ -358,4 +398,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

@ -217,7 +217,29 @@ public:
Java
```java
class Solution {
private int Deep = -1;
private int value = 0;
public int findBottomLeftValue(TreeNode root) {
value = root.val;
findLeftValue(root,0);
return value;
}
private void findLeftValue (TreeNode root,int deep) {
if (root == null) return;
if (root.left == null && root.right == null) {
if (deep > Deep) {
value = root.val;
Deep = deep;
}
}
if (root.left != null) findLeftValue(root.left,deep + 1);
if (root.right != null) findLeftValue(root.right,deep + 1);
}
}
```
Python
@ -231,4 +253,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

@ -148,6 +148,25 @@ public:
Java
```java
public class Solution {
public int longestPalindromeSubseq(String s) {
int len = s.length();
int[][] dp = new int[len + 1][len + 1];
for (int i = len - 1; i >= 0; i--) { // 从后往前遍历 保证情况不漏
dp[i][i] = 1; // 初始化
for (int j = i + 1; j < len; j++) {
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = Math.max(dp[i + 1][j], Math.max(dp[i][j], dp[i][j - 1]));
}
}
}
return dp[0][len - 1];
}
}
```
Python

View File

@ -151,7 +151,26 @@ public:
Java
```java
class Solution {
private TreeNode pre = null;
private int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
getMiniDiff(root);
return res;
}
private void getMiniDiff (TreeNode root) {
if (root == null) return;
getMiniDiff(root.left);
if (pre != null) {
res = Math.min(root.val - pre.val,res);
}
pre = root;
getMiniDiff(root.right);
}
}
```
Python
@ -165,4 +184,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

@ -173,7 +173,23 @@ public:
Java
```java
class Solution {
private int count = 0;
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
private void convert (TreeNode root) {
if (root == null) return;
convert(root.right);
count += root.val;
root.val = count;
convert(root.left);
}
}
```
Python
@ -187,4 +203,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

@ -256,7 +256,19 @@ public:
Java
```java
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) return root2;
if (root2 == null) return root1;
TreeNode newRoot = new TreeNode(root1.val + root2.val);
newRoot.left = mergeTrees(root1.left,root2.left);
newRoot.right = mergeTrees(root1.right,root2.right);
return newRoot;
}
}
```
Python
@ -270,4 +282,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,7 +224,31 @@ root->right = traversal(nums, maxValueIndex + 1, right);
Java
```java
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums.length == 0) return null;
return constructMaximumBinaryTree(nums,0,nums.length);
}
private TreeNode constructMaximumBinaryTree(int[] nums, int begin, int end) {
if (begin == end) return null;
int rootValue = nums[begin];
int index = begin;
for (int i = begin; i < end ; i++) {
if (nums[i] > rootValue) {
rootValue = nums[i];
index = i;
}
}
TreeNode root = new TreeNode(rootValue);
root.left = constructMaximumBinaryTree(nums, begin,index);
root.right = constructMaximumBinaryTree(nums,index+1,end);
return root;
}
}
```
Python
@ -238,4 +262,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

@ -242,7 +242,30 @@ public:
Java
```java
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
root = trim(root,low,high);
return root;
}
private static TreeNode trim(TreeNode root,int low, int high) {
if (root == null ) return null;
if (root.val < low) {
return trim(root.right,low,high);
}
if (root.val > high) {
return trim(root.left,low,high);
}
root.left = trim(root.left,low,high);
root.right = trim(root.right,low,high);
return root;
}
}
```
Python
@ -256,4 +279,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

@ -140,12 +140,61 @@ public:
## 其他语言版本
Java
递归法:
```java
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) return null;
if (root.val == val) return root;
else if (root.val > val) return searchBST(root.left, val);
else return searchBST(root.right, val);
}
}
```
迭代法:
```java
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while (root != null)
if (val < root.val) root = root.left;
else if (val > root.val) root = root.right;
else return root;
return root;
}
}
```
Python
递归法:
```python
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
if root is None:
return None
if val < root.val: return self.searchBST(root.left, val)
elif val > root.val: return self.searchBST(root.right, val)
else: return root
```
迭代法:
```python
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
while root is not None:
if val < root.val: root = root.left
elif val > root.val: root = root.right
else: return root
return root
```
Go
@ -156,4 +205,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

@ -16,7 +16,7 @@
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
![701.二叉搜索树中的插入操作](https://img-blog.csdnimg.cn/20201019173259554.png)
 
提示:
* 给定的树上的节点数介于 0 和 10^4 之间
@ -206,12 +206,69 @@ public:
## 其他语言版本
Java
```java
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
TreeNode newRoot = root;
TreeNode pre = root;
while (root != null) {
pre = root;
if (root.val > val) {
root = root.left;
} else if (root.val < val) {
root = root.right;
}
}
if (pre.val > val) {
pre.left = new TreeNode(val);
} else {
pre.right = new TreeNode(val);
}
return newRoot;
}
}
```
递归法
```java
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
return buildTree(root, val);
}
public TreeNode buildTree(TreeNode root, int val){
if (root == null) // 如果当前节点为空也就意味着val找到了合适的位置此时创建节点直接返回。
return new TreeNode(val);
if (root.val < val){
root.right = buildTree(root.right, val); // 递归创建右子树
}else if (root.val > val){
root.left = buildTree(root.left, val); // 递归创建左子树
}
return root;
}
}
```
Python
递归法
```python
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if root is None:
return TreeNode(val) # 如果当前节点为空也就意味着val找到了合适的位置此时创建节点直接返回。
if root.val < val:
root.right = self.insertIntoBST(root.right, val) # 递归创建右子树
if root.val > val:
root.left = self.insertIntoBST(root.left, val) # 递归创建左子树
return root
```
Go
@ -222,4 +279,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

@ -23,7 +23,7 @@
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
 
提示:
* 你可以假设 nums 中的所有元素是不重复的。
@ -146,11 +146,50 @@ public:
## 其他语言版本
Java
(版本一)左闭右闭区间
```java
class Solution {
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1;
else if (nums[mid] > target)
right = mid - 1;
}
return -1;
}
}
```
(版本二)左闭右开区间
```java
class Solution {
public int search(int[] nums, int target) {
int left = 0, right = nums.length;
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1;
else if (nums[mid] > target)
right = mid;
}
return -1;
}
}
```
Python
```python3
class Solution:
def search(self, nums: List[int], target: int) -> int:
@ -178,4 +217,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

@ -156,7 +156,23 @@ public:
Java
```java
class Solution {
public int maxProfit(int[] prices, int fee) {
int buy = prices[0] + fee;
int sum = 0;
for (int p : prices) {
if (p + fee < buy) {
buy = p + fee;
} else if (p > buy){
sum += p - buy;
buy = p;
}
}
return sum;
}
}
```
Python

View File

@ -125,6 +125,24 @@ public:
Java
```java
class Solution {
public int monotoneIncreasingDigits(int N) {
String[] strings = (N + "").split("");
int start = strings.length;
for (int i = strings.length - 1; i > 0; i--) {
if (Integer.parseInt(strings[i]) < Integer.parseInt(strings[i - 1])) {
strings[i - 1] = (Integer.parseInt(strings[i - 1]) - 1) + "";
start = i;
}
}
for (int i = start; i < strings.length; i++) {
strings[i] = "9";
}
return Integer.parseInt(String.join("",strings));
}
}
```
Python
@ -139,4 +157,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

@ -84,7 +84,28 @@ public:
Java
```java
class Solution {
public List<Integer> partitionLabels(String S) {
List<Integer> list = new LinkedList<>();
int[] edge = new int[123];
char[] chars = S.toCharArray();
for (int i = 0; i < chars.length; i++) {
edge[chars[i] - 0] = i;
}
int idx = 0;
int last = -1;
for (int i = 0; i < chars.length; i++) {
idx = Math.max(idx,edge[chars[i] - 0]);
if (i == idx) {
list.add(i - last);
last = i;
}
}
return list;
}
}
```
Python

View File

@ -127,7 +127,33 @@ public:
Java
```java
class Solution {
public boolean lemonadeChange(int[] bills) {
int cash_5 = 0;
int cash_10 = 0;
for (int i = 0; i < bills.length; i++) {
if (bills[i] == 5) {
cash_5++;
} else if (bills[i] == 10) {
cash_5--;
cash_10++;
} else if (bills[i] == 20) {
if (cash_10 > 0) {
cash_10--;
cash_5--;
} else {
cash_5 -= 3;
}
}
if (cash_5 < 0 || cash_10 < 0) return false;
}
return true;
}
}
```
Python
@ -141,4 +167,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

@ -316,6 +316,33 @@ public:
Java
```java
class Solution {
private int count = 0;
public int minCameraCover(TreeNode root) {
if (trval(root) == 0) count++;
return count;
}
private int trval(TreeNode root) {
if (root == null) return -1;
int left = trval(root.left);
int right = trval(root.right);
if (left == 0 || right == 0) {
count++;
return 2;
}
if (left == 2 || right == 2) {
return 1;
}
return 0;
}
}
```
Python
@ -330,4 +357,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

@ -29,7 +29,7 @@
输入A = [2,-3,-1,5,-4], K = 2
输出13
解释:选择索引 (1, 4) ,然后 A 变为 [2,3,-1,5,4]。
 
提示:
* 1 <= A.length <= 10000
@ -99,7 +99,29 @@ public:
Java
```java
class Solution {
public int largestSumAfterKNegations(int[] A, int K) {
if (A.length == 1) return A[0];
Arrays.sort(A);
int sum = 0;
int idx = 0;
for (int i = 0; i < K; i++) {
if (i < A.length - 1 && A[idx] < 0) {
A[idx] = -A[idx];
if (A[idx] >= Math.abs(A[idx + 1])) idx++;
continue;
}
A[idx] = -A[idx];
}
for (int i = 0; i < A.length; i++) {
sum += A[i];
}
return sum;
}
}
```
Python
@ -113,4 +135,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

@ -31,7 +31,7 @@
输入text1 = "abc", text2 = "def"
输出0
解释:两个字符串没有公共子序列,返回 0。
 
提示:
* 1 <= text1.length <= 1000
* 1 <= text2.length <= 1000
@ -126,12 +126,44 @@ public:
## 其他语言版本
Java
```java
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int[][] dp = new int[text1.length() + 1][text2.length() + 1]; // 先对dp数组做初始化操作
for (int i = 1 ; i <= text1.length() ; i++) {
char char1 = text1.charAt(i - 1);
for (int j = 1; j <= text2.length(); j++) {
char char2 = text2.charAt(j - 1);
if (char1 == char2) { // 开始列出状态转移方程
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[text1.length()][text2.length()];
}
}
```
Python
```python
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
len1, len2 = len(text1)+1, len(text2)+1
dp = [[0 for _ in range(len1)] for _ in range(len2)] # 先对dp数组做初始化操作
for i in range(1, len2):
for j in range(1, len1): # 开始列出状态转移方程
if text1[j-1] == text2[i-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]
```
Go
@ -142,4 +174,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

@ -7,6 +7,7 @@
<p align="center"><strong>欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
## 数组理论基础
数组是非常基础的数据结构,在面试中,考察数组的题目一般在思维上都不难,主要是考察对代码的掌控能力
@ -23,6 +24,8 @@
![算法通关数组](https://code-thinking.cdn.bcebos.com/pics/%E7%AE%97%E6%B3%95%E9%80%9A%E5%85%B3%E6%95%B0%E7%BB%84.png)
需要两点注意的是
* **数组下标都是从0开始的。**
@ -34,6 +37,7 @@
![算法通关数组1](https://code-thinking.cdn.bcebos.com/pics/%E7%AE%97%E6%B3%95%E9%80%9A%E5%85%B3%E6%95%B0%E7%BB%841.png)
而且大家如果使用C++的话要注意vector 和 array的区别vector的底层实现是array严格来讲vector是容器不是数组。
**数组的元素是不能删的,只能覆盖。**
@ -42,106 +46,79 @@
![算法通关数组2](https://code-thinking.cdn.bcebos.com/pics/%E7%AE%97%E6%B3%95%E9%80%9A%E5%85%B3%E6%95%B0%E7%BB%842.png)
**那么二维数组在内存的空间地址是连续的么?**
不同编程语言的内存管理是不一样的以C++为例在C++中二维数组是连续分布的,如图:
不同编程语言的内存管理是不一样的以C++为例在C++中二维数组是连续分布的
我们来做一个实验C++测试代码如下:
```C++
void test_arr() {
int array[2][3] = {
{0, 1, 2},
{3, 4, 5}
};
cout << &array[0][0] << " " << &array[0][1] << " " << &array[0][2] << endl;
cout << &array[1][0] << " " << &array[1][1] << " " << &array[1][2] << endl;
}
int main() {
test_arr();
}
```
测试地址为
```
0x7ffee4065820 0x7ffee4065824 0x7ffee4065828
0x7ffee406582c 0x7ffee4065830 0x7ffee4065834
```
注意地址为16进制可以看出二维数组地址是连续一条线的。
一些录友可能看不懂内存地址,我就简单介绍一下, 0x7ffee4065820 与 0x7ffee4065824 差了一个4就是4个字节因为这是一个int型的数组所以两个相信数组元素地址差4个字节。
0x7ffee4065828 与 0x7ffee406582c 也是差了4个字节在16进制里8 + 4 = cc就是12。
如图:
![数组内存](https://img-blog.csdnimg.cn/20210310150641186.png)
Java的二维数组可能是如下排列的方式
**所以可以看出在C++中二维数组在地址空间上是连续的**。
像Java是没有指针的同时也不对程序员暴漏其元素的地址寻址操作完全交给虚拟机。
所以看不到每个元素的地址情况这里我以Java为例也做一个实验。
```Java
public static void test_arr() {
int[][] arr = {{1, 2, 3}, {3, 4, 5}, {6, 7, 8}, {9,9,9}};
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
}
```
输出的地址为:
```
[I@7852e922
[I@4e25154f
[I@70dea4e
[I@5c647e05
```
这里的数值也是16进制这不是真正的地址而是经过处理过后的数值了我们也可以看出二维数组的每一行头结点的地址是没有规则的更谈不上连续。
所以Java的二维数组可能是如下排列的方式
![算法通关数组3](https://img-blog.csdnimg.cn/20201214111631844.png)
我们在[数组过于简单,但你该了解这些!](https://mp.weixin.qq.com/s/c2KABb-Qgg66HrGf8z-8Og)分别作了实验
这里面试中数组相关的理论知识就介绍完了。
## 数组的经典题目
在面试中,数组是必考的基础数据结构。
其实数据的题目在思想上一般比较简单的,但是如果想高效,并不容易。
我们之前一共讲解了四道经典数组题目,每一道题目都代表一个类型,一种思想。
### 二分法
[704.二分查找](https://mp.weixin.qq.com/s/4X-8VRgnYRGd5LYGZ33m4w)
在这道题目中我们讲到了**循环不变量原则**,只有在循环中坚持对区间的定义,才能清楚的把握循环中的各种细节。
**二分法是算法面试中的常考题,建议通过这道题目,锻炼自己手撕二分的能力**
相关题目:
* 35.搜索插入位置
* 34.在排序数组中查找元素的第一个和最后一个位置
* 69.x 的平方根
* 367.有效的完全平方数
### 双指针法
[27. 移除元素](https://mp.weixin.qq.com/s/RMkulE4NIb6XsSX83ra-Ww)
双指针法(快慢指针法):**通过一个快指针和慢指针在一个for循环下完成两个for循环的工作。**
暴力解法时间复杂度O(n^2)
双指针时间复杂度O(n)
这道题目迷惑了不少同学,纠结于数组中的元素为什么不能删除,主要是因为一下两点:
* 数组在内存中是连续的地址空间,不能释放单一元素,如果要释放,就是全释放(程序运行结束,回收内存栈空间)。
* C++中vector和array的区别一定要弄清楚vector的底层实现是array所以vector展现出友好的一些都是因为经过包装了。
双指针法(快慢指针法)在数组和链表的操作中是非常常见的,很多考察数组和链表操作的面试题,都使用双指针法。
相关题目:
* 26.删除排序数组中的重复项
* 283.移动零
* 844.比较含退格的字符串
* 977.有序数组的平方
### 滑动窗口
[209.长度最小的子数组](https://mp.weixin.qq.com/s/ewCRwVw0h0v4uJacYO7htQ)
本题介绍了数组操作中的另一个重要思想:滑动窗口。
暴力解法时间复杂度O(n^2)
滑动窗口时间复杂度O(n)
本题中,主要要理解滑动窗口如何移动 窗口起始位置,达到动态更新窗口大小的,从而得出长度最小的符合条件的长度。
**滑动窗口的精妙之处在于根据当前子序列和大小的情况不断调节子序列的起始位置。从而将O(n^2)的暴力解法降为O(n)。**
如果没有接触过这一类的方法,很难想到类似的解题思路,滑动窗口方法还是很巧妙的。
相关题目:
* 904.水果成篮
* 76.最小覆盖子串
### 模拟行为
[59.螺旋矩阵II](https://mp.weixin.qq.com/s/Hn6-mlCPvKAdWbiFfQyaaw)
模拟类的题目在数组中很常见,不涉及到什么算法,就是单纯的模拟,十分考察大家对代码的掌控能力。
在这道题目中,我们再一次介绍到了**循环不变量原则**,其实这也是写程序中的重要原则。
相信大家又遇到过这种情况: 感觉题目的边界调节超多,一波接着一波的判断,找边界,踩了东墙补西墙,好不容易运行通过了,代码写的十分冗余,毫无章法,其实**真正解决题目的代码都是简洁的,或者有原则性的**,大家可以在这道题目中体会到这一点。
相关题目:
* 54.螺旋矩阵
* 剑指Offer 29.顺时针打印矩阵
## 总结
从二分法到双指针,从滑动窗口到螺旋矩阵,相信如果大家真的认真做了「代码随想录」每日推荐的题目,定会有所收获。
**每道题目后面都有相关练习题,也别忘了去做做!**
数组专题中讲解和相关题目已经有16道了就不介绍太过题目了因为数组是非常基础的数据结构后面很多专题还会用到数组所以后面的题目依然会会间接练习数组的。
后续我将介绍面试中数组相关的五道经典面试题目,敬请期待!
## 其他语言版本