diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 0beb45cf..06367851 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -182,7 +182,45 @@ class Solution { ``` Python: +```python3 +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + res = [] #存放符合条件结果的集合 + path = [] #用来存放符合条件的结果 + used = [] #用来存放已经用过的数字 + def backtrack(nums,used): + if len(path) == len(nums): + return res.append(path[:]) #此时说明找到了一组 + for i in range(0,len(nums)): + if nums[i] in used: + continue #used里已经收录的元素,直接跳过 + path.append(nums[i]) + used.append(nums[i]) + backtrack(nums,used) + used.pop() + path.pop() + backtrack(nums,used) + return res +``` +Python(优化,不用used数组): +```python3 +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + res = [] #存放符合条件结果的集合 + path = [] #用来存放符合条件的结果 + def backtrack(nums): + if len(path) == len(nums): + return res.append(path[:]) #此时说明找到了一组 + for i in range(0,len(nums)): + if nums[i] in path: #path里已经收录的元素,直接跳过 + continue + path.append(nums[i]) + backtrack(nums) #递归 + path.pop() #回溯 + backtrack(nums) + return res +``` Go: ```Go diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index b4b42a4a..8618515e 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -141,7 +141,20 @@ func canJUmp(nums []int) bool { } ``` - +Javascript: +```Javascript +var canJump = function(nums) { + if(nums.length === 1) return true + let cover = 0 + for(let i = 0; i <= cover; i++) { + cover = Math.max(cover, i + nums[i]) + if(cover >= nums.length - 1) { + return true + } + } + return false +}; +``` ----------------------- diff --git a/problems/0078.子集.md b/problems/0078.子集.md index 17c4fb5c..0b2f3c09 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -205,7 +205,20 @@ class Solution { ``` Python: - +```python3 +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + res = [] + path = [] + def backtrack(nums,startIndex): + res.append(path[:]) #收集子集,要放在终止添加的上面,否则会漏掉自己 + for i in range(startIndex,len(nums)): #当startIndex已经大于数组的长度了,就终止了,for循环本来也结束了,所以不需要终止条件 + path.append(nums[i]) + backtrack(nums,i+1) #递归 + path.pop() #回溯 + backtrack(nums,0) + return res +``` Go: ```Go diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 6b12a95b..71aef5c7 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -208,7 +208,23 @@ class Solution { ``` Python: - +```python3 +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + res = [] #存放符合条件结果的集合 + path = [] #用来存放符合条件结果 + def backtrack(nums,startIndex): + res.append(path[:]) + for i in range(startIndex,len(nums)): + if i > startIndex and nums[i] == nums[i - 1]: #我们要对同一树层使用过的元素进行跳过 + continue + path.append(nums[i]) + backtrack(nums,i+1) #递归 + path.pop() #回溯 + nums = sorted(nums) #去重需要排序 + backtrack(nums,0) + return res +``` Go: ```Go diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index 15c2d1f9..9deb1e0c 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -234,25 +234,19 @@ class Solution: ``` Go: -```func detectCycle(head *ListNode) *ListNode { - if head ==nil{ - return head - } - slow:=head - fast:=head.Next - - for fast!=nil&&fast.Next!=nil{ - if fast==slow{ - slow=head - fast=fast.Next - for fast!=slow { - fast=fast.Next - slow=slow.Next +```go +func detectCycle(head *ListNode) *ListNode { + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + if slow == fast { + for slow != head { + slow = slow.Next + head = head.Next } - return slow + return head } - fast=fast.Next.Next - slow=slow.Next } return nil } diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index e38bc1a3..c8b0da08 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -224,6 +224,22 @@ var evalRPN = function(tokens) { }; ``` +python3 + +```python +def evalRPN(tokens) -> int: + stack = list() + for i in range(len(tokens)): + if tokens[i] not in ["+", "-", "*", "/"]: + stack.append(tokens[i]) + else: + tmp1 = stack.pop() + tmp2 = stack.pop() + res = eval(tmp2+tokens[i]+tmp1) + stack.append(str(int(res))) + return stack[-1] +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 10314a08..c2af71f7 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -282,6 +282,50 @@ class MyQueue { Python: +```python +# 使用两个栈实现先进先出的队列 +class MyQueue: + def __init__(self): + """ + Initialize your data structure here. + """ + self.stack1 = list() + self.stack2 = list() + + def push(self, x: int) -> None: + """ + Push element x to the back of queue. + """ + # self.stack1用于接受元素 + self.stack1.append(x) + + def pop(self) -> int: + """ + Removes the element from in front of queue and returns that element. + """ + # self.stack2用于弹出元素,如果self.stack2为[],则将self.stack1中元素全部弹出给self.stack2 + if self.stack2 == []: + while self.stack1: + tmp = self.stack1.pop() + self.stack2.append(tmp) + return self.stack2.pop() + + def peek(self) -> int: + """ + Get the front element. + """ + if self.stack2 == []: + while self.stack1: + tmp = self.stack1.pop() + self.stack2.append(tmp) + return self.stack2[-1] + + def empty(self) -> bool: + """ + Returns whether the queue is empty. + """ + return self.stack1 == [] and self.stack2 == [] +``` Go: diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index c9423a1a..fefaa293 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -51,10 +51,6 @@ dp[i]的定义讲贯彻整个解题过程,下面哪一步想不懂了,就想 **那有同学问了,j怎么就不拆分呢?** -j是从1开始遍历,拆分j的情况,在遍历j的过程中其实都计算过了。 - -**那有同学问了,j怎么就不拆分呢?** - j是从1开始遍历,拆分j的情况,在遍历j的过程中其实都计算过了。那么从1遍历j,比较(i - j) * j和dp[i - j] * j 取最大的。递推公式:dp[i] = max(dp[i], max((i - j) * j, dp[i - j] * j)); 也可以这么理解,j * (i - j) 是单纯的把整数拆分为两个数相乘,而j * dp[i - j]是拆分成两个以及两个以上的个数相乘。 @@ -213,8 +209,19 @@ class Solution { ``` Python: - - +```python +class Solution: + def integerBreak(self, n: int) -> int: + dp = [0] * (n + 1) + dp[2] = 1 + for i in range(3, n + 1): + # 假设对正整数 i 拆分出的第一个正整数是 j(1 <= j < i),则有以下两种方案: + # 1) 将 i 拆分成 j 和 i−j 的和,且 i−j 不再拆分成多个正整数,此时的乘积是 j * (i-j) + # 2) 将 i 拆分成 j 和 i−j 的和,且 i−j 继续拆分成多个正整数,此时的乘积是 j * dp[i-j] + for j in range(1, i): + dp[i] = max(dp[i], max(j * (i - j), j * dp[i - j])) + return dp[n] +``` Go: diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 30d702b4..e5daa9db 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -226,7 +226,51 @@ class Solution: ``` Go: - +JavaScript: +递归版本 +```javascript +var sumOfLeftLeaves = function(root) { + //采用后序遍历 递归遍历 + // 1. 确定递归函数参数 + const nodesSum = function(node){ + // 2. 确定终止条件 + if(node===null){ + return 0; + } + let leftValue = sumOfLeftLeaves(node.left); + let rightValue = sumOfLeftLeaves(node.right); + // 3. 单层递归逻辑 + let midValue = 0; + if(node.left&&node.left.left===null&&node.left.right===null){ + midValue = node.left.val; + } + let sum = midValue + leftValue + rightValue; + return sum; + } + return nodesSum(root); +}; +``` +迭代版本 +```javascript +var sumOfLeftLeaves = function(root) { + //采用层序遍历 + if(root===null){ + return null; + } + let queue = []; + let sum = 0; + queue.push(root); + while(queue.length){ + let node = queue.shift(); + if(node.left!==null&&node.left.left===null&&node.left.right===null){ + sum+=node.left.val; + } + node.left&&queue.push(node.left); + node.right&&queue.push(node.right); + } + return sum; +}; +``` diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 691f7aef..5538a2c9 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -229,7 +229,28 @@ class Solution { Python: - +```python3 +class Solution: + def findSubsequences(self, nums: List[int]) -> List[List[int]]: + res = [] + path = [] + def backtrack(nums,startIndex): + repeat = [] #这里使用数组来进行去重操作 + if len(path) >=2: + res.append(path[:]) #注意这里不要加return,要取树上的节点 + for i in range(startIndex,len(nums)): + if nums[i] in repeat: + continue + if len(path) >= 1: + if nums[i] < path[-1]: + continue + repeat.append(nums[i]) #记录这个元素在本层用过了,本层后面不能再用了 + path.append(nums[i]) + backtrack(nums,i+1) + path.pop() + backtrack(nums,0) + return res +``` Go: diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index db53caf7..6c8f3e94 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -106,27 +106,24 @@ Java: class Solution { public String reverseStr(String s, int k) { StringBuffer res = new StringBuffer(); - - for (int i = 0; i < s.length(); i += (2 * k)) { + int length = s.length(); + int start = 0; + while (start < length) { + // 找到k处和2k处 StringBuffer temp = new StringBuffer(); - // 剩余字符大于 k 个,每隔 2k 个字符的前 k 个字符进行反转 - if (i + k <= s.length()) { - // 反转前 k 个字符 - temp.append(s.substring(i, i + k)); - res.append(temp.reverse()); + // 与length进行判断,如果大于length了,那就将其置为length + int firstK = (start + k > length) ? length : start + k; + int secondK = (start + (2 * k) > length) ? length : start + (2 * k); - // 反转完前 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())); + //无论start所处位置,至少会反转一次 + temp.append(s.substring(start, firstK)); res.append(temp.reverse()); + + // 如果firstK到secondK之间有元素,这些元素直接放入res里即可。 + if (firstK < secondK) { //此时剩余长度一定大于k。 + res.append(s.substring(firstK, secondK)); + } + start += (2 * k); } return res.toString(); } diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 167a258c..b5d392e6 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -100,10 +100,66 @@ public: Java: Python: - +```Python +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + n = len(nums) + i,j,k = 0,n - 1,n - 1 + ans = [-1] * n + while i <= j: + lm = nums[i] ** 2 + rm = nums[j] ** 2 + if lm > rm: + ans[k] = lm + i += 1 + else: + ans[k] = rm + j -= 1 + k -= 1 + return ans +``` Go: - +```Go +func sortedSquares(nums []int) []int { + n := len(nums) + i, j, k := 0, n-1, n-1 + ans := make([]int, n) + for i <= j { + lm, rm := nums[i]*nums[i], nums[j]*nums[j] + if lm > rm { + ans[k] = lm + i++ + } else { + ans[k] = rm + j-- + } + k-- + } + return ans +} +``` +Rust +``` +impl Solution { + pub fn sorted_squares(nums: Vec) -> Vec { + let n = nums.len(); + let (mut i,mut j,mut k) = (0,n - 1,n- 1); + let mut ans = vec![0;n]; + while i <= j{ + if nums[i] * nums[i] < nums[j] * nums[j] { + ans[k] = nums[j] * nums[j]; + j -= 1; + }else{ + ans[k] = nums[i] * nums[i]; + i += 1; + } + k -= 1; + } + ans + } +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 9e97264c..13014dd1 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -155,6 +155,42 @@ Python: Go: +```go +func getIntersectionNode(headA, headB *ListNode) *ListNode { + curA := headA + curB := headB + lenA, lenB := 0, 0 + // 求A,B的长度 + for curA != nil { + curA = curA.Next + lenA++ + } + for curB != nil { + curB = curB.Next + lenB++ + } + var step int + var fast, slow *ListNode + // 请求长度差,并且让更长的链表先走相差的长度 + if lenA > lenB { + step = lenA - lenB + fast, slow = headA, headB + } else { + step = lenB - lenA + fast, slow = headB, headA + } + for i:=0; i < step; i++ { + fast = fast.Next + } + // 遍历两个链表遇到相同则跳出遍历 + for fast != slow { + fast = fast.Next + slow = slow.Next + } + return fast +} +``` + javaScript: ```js