diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 55e22887..96dc1ac3 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -221,6 +221,40 @@ Python: Go: +```Go +func threeSum(nums []int)[][]int{ + sort.Ints(nums) + res:=[][]int{} + + for i:=0;i0{ + break + } + if i>0&&n1==nums[i-1]{ + continue + } + l,r:=i+1,len(nums)-1 + for l list = new ArrayList<>(); + + public List letterCombinations(String digits) { + if (digits == null || digits.length() == 0) { + return list; + } + //初始对应所有的数字,为了直接对应2-9,新增了两个无效的字符串"" + String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + //迭代处理 + backTracking(digits, numString, 0); + return list; + + } + + //每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuild + StringBuilder temp = new StringBuilder(); + + //比如digits如果为"23",num 为0,则str表示2对应的 abc + public void backTracking(String digits, String[] numString, int num) { + //遍历全部一次记录一次得到的字符串 + if (num == digits.length()) { + list.add(temp.toString()); + return; + } + //str 表示当前num对应的字符串 + String str = numString[digits.charAt(num) - '0']; + for (int i = 0; i < str.length(); i++) { + temp.append(str.charAt(i)); + //回溯 + backTracking(digits, numString, num + 1); + //剔除末尾的继续尝试 + temp.deleteCharAt(temp.length() - 1); + } + } +} +``` Python: diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index 3b6dde1e..3b89dabd 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -112,7 +112,28 @@ class Solution { } } ``` +Go: +```Go +func removeNthFromEnd(head *ListNode, n int) *ListNode { + result:=&ListNode{} + result.Next=head + var pre *ListNode + cur:=result + i:=1 + for head!=nil{ + if i>=n{ + pre=cur + cur=cur.Next + } + head=head.Next + i++ + } + pre.Next=pre.Next.Next + return result.Next + +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index f2d78ade..9f6c8487 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -138,7 +138,31 @@ public: Java: - +```Java +class Solution { + public boolean isValid(String s) { + Deque deque = new LinkedList<>(); + char ch; + for (int i = 0; i < s.length(); i++) { + ch = s.charAt(i); + //碰到左括号,就把相应的右括号入栈 + if (ch == '(') { + deque.push(')'); + }else if (ch == '{') { + deque.push('}'); + }else if (ch == '[') { + deque.push(']'); + } else if (deque.isEmpty() || deque.peek() != ch) { + return false; + }else {//如果是右括号判断是否和栈顶元素匹配 + deque.pop(); + } + } + //最后判断栈中元素是否匹配 + return deque.isEmpty(); + } +} +``` Python: ```python3 @@ -157,7 +181,26 @@ class Solution: ``` Go: +```Go +func isValid(s string) bool { + hash := map[byte]byte{')':'(', ']':'[', '}':'{'} + stack := make([]byte, 0) + if s == "" { + return true + } + for i := 0; i < len(s); i++ { + if s[i] == '(' || s[i] == '[' || s[i] == '{' { + stack = append(stack, s[i]) + } else if len(stack) > 0 && stack[len(stack)-1] == hash[s[i]] { + stack = stack[:len(stack)-1] + } else { + return false + } + } + return len(stack) == 0 +} +``` diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 144cd5be..959474fc 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -124,9 +124,19 @@ public: Java: - Python: +```python +class Solution: + def removeElement(self, nums: List[int], val: int) -> int: + i,n = 0,len(nums) + for j in range(n): + if nums[j] != val: + nums[i] = nums[j] + i += 1 + return i +``` + Go: ```go @@ -162,4 +172,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) -
+
\ No newline at end of file diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index c351e365..e891e3c5 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -237,6 +237,22 @@ class Solution { Python: +```python3 +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + left, right = 0, len(nums) - 1 + + while left <= right: + middle = (left + right) // 2 + + if nums[middle] < target: + left = middle + 1 + elif nums[middle] > target: + right = middle - 1 + else: + return middle + return right + 1 +``` Go: diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index b8b11a57..6474d01f 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -160,11 +160,44 @@ class Solution { ``` Python: - +```python +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + result = -float('inf') + count = 0 + for i in range(len(nums)): + count += nums[i] + if count > result: + result = count + if count <= 0: + count = 0 + return result +``` Go: +```Go +func maxSubArray(nums []int) int { + if len(nums)<1{ + return 0 + } + dp:=make([]int,len(nums)) + result:=nums[0] + dp[0]=nums[0] + for i:=1;ib{ + return a + }else{ + return b + } +} +``` ----------------------- diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index 6ae6adc7..f0a08f99 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -230,7 +230,20 @@ class Solution: ``` Go: - +```Go +func climbStairs(n int) int { + if n==1{ + return 1 + } + dp:=make([]int,n+1) + dp[1]=1 + dp[2]=2 + for i:=3;i<=n;i++{ + dp[i]=dp[i-1]+dp[i-2] + } + return dp[n] +} +``` diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index 2af123d1..a8a17858 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -147,7 +147,33 @@ public: Java: +``` +class Solution { + List> result = new ArrayList<>(); + LinkedList path = new LinkedList<>(); + public List> combine(int n, int k) { + combineHelper(n, k, 1); + return result; + } + /** + * 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex + * @param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。 + */ + private void combineHelper(int n, int k, int startIndex){ + //终止条件 + if (path.size() == k){ + result.add(new ArrayList<>(path)); + return; + } + for (int i = startIndex; i <= n - (k - path.size()) + 1; i++){ + path.add(i); + combineHelper(n, k, i + 1); + path.removeLast(); + } + } +} +``` Python: diff --git a/problems/0078.子集.md b/problems/0078.子集.md index a61d7493..7166f7fa 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -209,6 +209,28 @@ Python: Go: +```Go +var res [][]int +func subset(nums []int) [][]int { + res = make([][]int, 0) + sort.Ints(nums) + Dfs([]int{}, nums, 0) + return res +} +func Dfs(temp, nums []int, start int){ + tmp := make([]int, len(temp)) + copy(tmp, temp) + res = append(res, tmp) + for i := start; i < len(nums); i++{ + //if i>start&&nums[i]==nums[i-1]{ + // continue + //} + temp = append(temp, nums[i]) + Dfs(temp, nums, i+1) + temp = temp[:len(temp)-1] + } +} +``` Javascript: diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md index 2764277c..7dea8fb0 100644 --- a/problems/0096.不同的二叉搜索树.md +++ b/problems/0096.不同的二叉搜索树.md @@ -165,7 +165,25 @@ public: Java: - +```Java +class Solution { + public int numTrees(int n) { + //初始化 dp 数组 + int[] dp = new int[n + 1]; + //初始化0个节点和1个节点的情况 + dp[0] = 1; + dp[1] = 1; + for (int i = 2; i <= n; i++) { + for (int j = 1; j <= i; j++) { + //对于第i个节点,需要考虑1作为根节点直到i作为根节点的情况,所以需要累加 + //一共i个节点,对于根节点j时,左子树的节点个数为j-1,右子树的节点个数为i-j + dp[i] += dp[j - 1] * dp[i - j]; + } + } + return dp[n]; + } +} +``` Python: diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index baa3f435..ddd634b4 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -260,7 +260,25 @@ Python: Go: +```Go +import "math" +func isValidBST(root *TreeNode) bool { + if root == nil { + return true + } + return isBST(root, math.MinInt64, math.MaxFloat64) +} +func isBST(root *TreeNode, min, max int) bool { + if root == nil { + return true + } + if min >= root.Val || max <= root.Val { + return false + } + return isBST(root.Left, min, root.Val) && isBST(root.Right, root.Val, max) +} +``` diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 561d0470..535300af 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -253,7 +253,6 @@ public: ## 其他语言版本 - Java: @@ -284,4 +283,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) -
+
\ No newline at end of file diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index be2e9dca..0781e01d 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -419,18 +419,17 @@ public: Java: -``` Java - - +```Java class Solution { public List> resList=new ArrayList>(); public List> levelOrder(TreeNode root) { - checkFun01(root,0); - + //checkFun01(root,0); + checkFun02(root); + return resList; } - //递归方式 + //DFS--递归方式 public void checkFun01(TreeNode node,Integer deep){ if(node==null) return; deep++; @@ -442,12 +441,33 @@ class Solution { } 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 que=new LinkedList(); + que.offer(node); + while(!que.isEmpty()){ + List itemList=new ArrayList(); + int len=que.size(); + 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); + len--; + } + + resList.add(itemList); + } + + } ``` @@ -458,7 +478,6 @@ Go: - ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 5d55910c..ac66cc40 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -353,7 +353,6 @@ public: ## 其他语言版本 - Java: @@ -361,7 +360,40 @@ Python: Go: - +```Go +func isBalanced(root *TreeNode) bool { + if root==nil{ + return true + } + if !isBalanced(root.Left) || !isBalanced(root.Right){ + return false + } + LeftH:=maxdepth(root.Left)+1 + RightH:=maxdepth(root.Right)+1 + if abs(LeftH-RightH)>1{ + return false + } + return true +} +func maxdepth(root *TreeNode)int{ + if root==nil{ + return 0 + } + return max(maxdepth(root.Left),maxdepth(root.Right))+1 +} +func max(a,b int)int{ + if a>b{ + return a + } + return b +} +func abs(a int)int{ + if a<0{ + return -a + } + return a +} +``` @@ -369,4 +401,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
+
\ No newline at end of file diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 430cd5d6..6c6b4632 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -195,9 +195,51 @@ public: Java: - Python: +递归法: + +```python +class Solution: + def minDepth(self, root: TreeNode) -> int: + if not root: + return 0 + if not root.left and not root.right: + return 1 + + min_depth = 10**9 + if root.left: + min_depth = min(self.minDepth(root.left), min_depth) # 获得左子树的最小高度 + if root.right: + min_depth = min(self.minDepth(root.right), min_depth) # 获得右子树的最小高度 + return min_depth + 1 +``` + +迭代法: + +```python +class Solution: + def minDepth(self, root: TreeNode) -> int: + if not root: + return 0 + que = deque() + que.append(root) + res = 1 + + while que: + for _ in range(len(que)): + node = que.popleft() + # 当左右孩子都为空的时候,说明是最低点的一层了,退出 + if not node.left and not node.right: + return res + if node.left is not None: + que.append(node.left) + if node.right is not None: + que.append(node.right) + res += 1 + return res +``` + Go: @@ -208,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) -
+
\ No newline at end of file diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 01ff35c5..9c86a3bc 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -250,7 +250,46 @@ public: Java: +```Java +class Solution { + List> lists = new ArrayList<>(); + Deque deque = new LinkedList<>(); + public List> partition(String s) { + backTracking(s, 0); + return lists; + } + + private void backTracking(String s, int startIndex) { + //如果起始位置大于s的大小,说明找到了一组分割方案 + if (startIndex >= s.length()) { + lists.add(new ArrayList(deque)); + return; + } + for (int i = startIndex; i < s.length(); i++) { + //如果是回文子串,则记录 + if (isPalindrome(s, startIndex, i)) { + String str = s.substring(startIndex, i + 1); + deque.addLast(str); + } else { + continue; + } + //起始位置后移,保证不重复 + backTracking(s, i + 1); + deque.removeLast(); + } + } + //判断是否是回文串 + private boolean isPalindrome(String s, int startIndex, int end) { + for (int i = startIndex, j = end; i < j; i++, j--) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } + } + return true; + } +} +``` Python: diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index b9ccec45..c64648ad 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -117,6 +117,33 @@ Python: Go: +```Go +func rob(nums []int) int { + if len(nums)<1{ + return 0 + } + if len(nums)==1{ + return nums[0] + } + if len(nums)==2{ + return max(nums[0],nums[1]) + } + dp :=make([]int,len(nums)) + dp[0]=nums[0] + dp[1]=max(nums[0],nums[1]) + for i:=2;ib{ + return a + } + return b +} +``` diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 49b5c62b..4018364a 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -154,9 +154,58 @@ public: ## 其他语言版本 - Java: +```java +class MyStack { + + Queue queue1; // 和栈中保持一样元素的队列 + Queue queue2; // 辅助队列 + + /** Initialize your data structure here. */ + public MyStack() { + queue1 = new LinkedList<>(); + queue2 = new LinkedList<>(); + } + + /** Push element x onto stack. */ + public void push(int x) { + queue2.offer(x); // 先放在辅助队列中 + while (!queue1.isEmpty()){ + queue2.offer(queue1.poll()); + } + Queue queueTemp; + queueTemp = queue1; + queue1 = queue2; + queue2 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中 + } + + /** Removes the element on top of the stack and returns that element. */ + public int pop() { + return queue1.poll(); // 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可 + } + + /** Get the top element. */ + public int top() { + return queue1.peek(); + } + + /** Returns whether the stack is empty. */ + public boolean empty() { + return queue1.isEmpty(); + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */ +``` + Python: @@ -227,4 +276,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
+
\ No newline at end of file diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index afc1f144..ec1335c6 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -208,8 +208,21 @@ Java: Python: -Go: +```Go +func invertTree(root *TreeNode) *TreeNode { + if root ==nil{ + return nil + } + temp:=root.Left + root.Left=root.Right + root.Right=temp + + invertTree(root.Left) + invertTree(root.Right) + return root +} +``` diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 9907b476..abdc363d 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -19,7 +19,7 @@ push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。 -  + 示例: @@ -129,9 +129,62 @@ public: ## 其他语言版本 - Java: +```java +class MyQueue { + + Stack stack1; + Stack stack2; + + /** Initialize your data structure here. */ + public MyQueue() { + stack1 = new Stack<>(); // 负责进栈 + stack2 = new Stack<>(); // 负责出栈 + } + + /** Push element x to the back of queue. */ + public void push(int x) { + stack1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + public int pop() { + dumpStack1(); + return stack2.pop(); + } + + /** Get the front element. */ + public int peek() { + dumpStack1(); + return stack2.peek(); + } + + /** Returns whether the queue is empty. */ + public boolean empty() { + return stack1.isEmpty() && stack2.isEmpty(); + } + + // 如果stack2为空,那么将stack1中的元素全部放到stack2中 + private void dumpStack1(){ + if (stack2.isEmpty()){ + while (!stack1.isEmpty()){ + stack2.push(stack1.pop()); + } + } + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */ +``` + Python: @@ -145,4 +198,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
+
\ No newline at end of file diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 709fa09e..781bfa6f 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -207,7 +207,60 @@ public: Java: +```Java +//自定义数组 +class MyQueue { + Deque deque = new LinkedList<>(); + //弹出元素时,比较当前要弹出的数值是否等于队列出口的数值,如果相等则弹出 + //同时判断队列当前是否为空 + void poll(int val) { + if (!deque.isEmpty() && val == deque.peek()) { + deque.poll(); + } + } + //添加元素时,如果要添加的元素大于入口处的元素,就将入口元素弹出 + //保证队列元素单调递减 + //比如此时队列元素3,1,2将要入队,比1大,所以1弹出,此时队列:3,2 + void add(int val) { + while (!deque.isEmpty() && val > deque.getLast()) { + deque.removeLast(); + } + deque.add(val); + } + //队列队顶元素始终为最大值 + int peek() { + return deque.peek(); + } +} +class Solution { + public int[] maxSlidingWindow(int[] nums, int k) { + if (nums.length == 1) { + return nums; + } + int len = nums.length - k + 1; + //存放结果元素的数组 + int[] res = new int[len]; + int num = 0; + //自定义队列 + MyQueue myQueue = new MyQueue(); + //先将前k的元素放入队列 + for (int i = 0; i < k; i++) { + myQueue.add(nums[i]); + } + res[num++] = myQueue.peek(); + for (int i = k; i < nums.length; i++) { + //滑动窗口移除最前面的元素,移除是判断该元素是否放入队列 + myQueue.poll(nums[i - k]); + //滑动窗口加入最后面的元素 + myQueue.add(nums[i]); + //记录对应的最大值 + res[num++] = myQueue.peek(); + } + return res; + } +} +``` Python: diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md index 39260926..d72e9099 100644 --- a/problems/0279.完全平方数.md +++ b/problems/0279.完全平方数.md @@ -159,7 +159,28 @@ public: Java: - +```Java +class Solution { + public int numSquares(int n) { + int max = Integer.MAX_VALUE; + int[] dp = new int[n + 1]; + //初始化 + for (int j = 0; j <= n; j++) { + dp[j] = max; + } + //当和为0时,组合的个数为0 + dp[0] = 0; + for (int i = 1; i * i <= n; i++) { + for (int j = i * i; j <= n; j++) { + if (dp[j - i * i] != max) { + dp[j] = Math.min(dp[j], dp[j - i * i] + 1); + } + } + } + return dp[n]; + } +} +``` Python: diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index ddb9805d..b4c843b7 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -140,12 +140,37 @@ public: Java: - +```Java +class Solution { + public void reverseString(char[] s) { + int l = 0; + int r = s.length - 1; + while (l < r) { + s[l] ^= s[r]; //构造 a ^ b 的结果,并放在 a 中 + s[r] ^= s[l]; //将 a ^ b 这一结果再 ^ b ,存入b中,此时 b = a, a = a ^ b + s[l] ^= s[r]; //a ^ b 的结果再 ^ a ,存入 a 中,此时 b = a, a = b 完成交换 + l++; + r--; + } + } +} +``` Python: Go: +```Go +func reverseString(s []byte) { + left:=0 + right:=len(s)-1 + for left record = new HashSet(); - Set unique = new HashSet(); - - for (int num : nums1) { - record.add(num); + if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) { + return new int[0]; } - - for (int num : nums2) { - if (record.contains(num)) { - unique.add(num); + Set set1 = new HashSet<>(); + Set resSet = new HashSet<>(); + //遍历数组1 + for (int i : nums1) { + set1.add(i); + } + //遍历数组2的过程中判断哈希表中是否存在该元素 + for (int i : nums2) { + if (set1.contains(i)) { + resSet.add(i); } } - - int[] res = new int[unique.size()]; + int[] resArr = new int[resSet.size()]; int index = 0; - for (int num : unique) { - res[index++] = num; + //将结果几何转为数组 + for (int i : resSet) { + resArr[index++] = i; } - return res; + return resArr; } } ``` diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 6ae76526..fa90142d 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -111,7 +111,31 @@ public: Java: - +```Java +class Solution { + public int wiggleMaxLength(int[] nums) { + if (nums == null || nums.length <= 1) { + return nums.length; + } + //当前差值 + int curDiff = 0; + //上一个差值 + int preDiff = 0; + int count = 1; + for (int i = 1; i < nums.length; i++) { + //得到当前差值 + curDiff = nums[i] - nums[i - 1]; + //如果当前差值和上一个差值为一正一负 + //等于0的情况表示初始时的preDiff + if ((curDiff > 0 && preDiff <= 0) || (curDiff < 0 && preDiff >= 0)) { + count++; + preDiff = curDiff; + } + } + return count; + } +} +``` Python: diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 8ff2b320..da4ed666 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -159,9 +159,51 @@ public: ## 其他语言版本 - Java: +**递归** + +```java +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) return 0; + int leftValue = sumOfLeftLeaves(root.left); // 左 + int rightValue = sumOfLeftLeaves(root.right); // 右 + + int midValue = 0; + if (root.left != null && root.left.left == null && root.left.right == null) { // 中 + midValue = root.left.val; + } + int sum = midValue + leftValue + rightValue; + return sum; + } +} +``` + +**迭代** + +```java +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) return 0; + Stack stack = new Stack<> (); + stack.add(root); + int result = 0; + while (!stack.isEmpty()) { + TreeNode node = stack.pop(); + if (node.left != null && node.left.left == null && node.left.right == null) { + result += node.left.val; + } + if (node.right != null) stack.add(node.right); + if (node.left != null) stack.add(node.left); + } + return result; + } +} +``` + + + Python: @@ -176,3 +218,4 @@ Go: * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
+ diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index ed0cb9d7..6e38b4fe 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -257,6 +257,44 @@ Python: Go: +```Go +func deleteNode(root *TreeNode, key int) *TreeNode { + if root==nil{ + return nil + } + if keyroot.Val{ + root.Right=deleteNode(root.Right,key) + return root + } + if root.Right==nil{ + return root.Left + } + if root.Left==nil{ + return root.Right + } + minnode:=root.Right + for minnode.Left!=nil{ + minnode=minnode.Left + } + root.Val=minnode.Val + root.Right=deleteNode1(root.Right) + return root +} + +func deleteNode1(root *TreeNode)*TreeNode{ + if root.Left==nil{ + pRight:=root.Right + root.Right=nil + return pRight + } + root.Left=deleteNode1(root.Left) + return root +} +``` diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 893c92f9..0a92ac8b 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -102,7 +102,36 @@ public: Java: +```Java +class Solution { + public String reverseStr(String s, int k) { + StringBuffer res = new StringBuffer(); + for (int i = 0; i < s.length(); i += (2 * k)) { + StringBuffer temp = new StringBuffer(); + // 剩余字符大于 k 个,每隔 2k 个字符的前 k 个字符进行反转 + if (i + k <= s.length()) { + // 反转前 k 个字符 + temp.append(s.substring(i, i + k)); + res.append(temp.reverse()); + + // 反转完前 k 个字符之后,如果紧接着还有 k 个字符,则直接加入这 k 个字符 + if (i + 2 * k <= s.length()) { + res.append(s.substring(i + k, i + 2 * k)); + // 不足 k 个字符,则直接加入剩下所有字符 + } else { + res.append(s.substring(i + k, s.length())); + } + continue; + } + // 剩余字符少于 k 个,则将剩余字符全部反转。 + temp.append(s.substring(i, s.length())); + res.append(temp.reverse()); + } + return res.toString(); + } +} +``` Python: diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 7a06f02d..d5a8c4ed 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -122,7 +122,28 @@ public: Java: - +```Java +class Solution { + public String removeDuplicates(String S) { + Deque deque = new LinkedList<>(); + char ch; + for (int i = 0; i < S.length(); i++) { + ch = S.charAt(i); + if (deque.isEmpty() || deque.peek() != ch) { + deque.push(ch); + } else { + deque.pop(); + } + } + String str = ""; + //剩余的元素即为不重复的元素 + while (!deque.isEmpty()) { + str = deque.pop() + str; + } + return str; + } +} +``` Python: diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 7881adf3..5f89241b 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -129,7 +129,26 @@ for (int i = 0; i < a.size(); i++) { Java: - +```Java +//使用一个新的对象,复制 str,复制的过程对其判断,是空格则替换,否则直接复制,类似于数组复制 +public static String replaceSpace(StringBuffer str) { + if (str == null) { + return null; + } + //选用 StringBuilder 单线程使用,比较快,选不选都行 + StringBuilder sb = new StringBuilder(); + //使用 sb 逐个复制 str ,碰到空格则替换,否则直接复制 + for (int i = 0; i < str.length(); i++) { + //str.charAt(i) 为 char 类型,为了比较需要将其转为和 " " 相同的字符串类型 + if (" ".equals(String.valueOf(str.charAt(i)))){ + sb.append("%20"); + } else { + sb.append(str.charAt(i)); + } + } + return sb.toString(); + } +``` Python: