classSolution(object): defminDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int""" if word1 == ''or word2 == '': return len(word1) if word1 != ''else len(word2) dp = [[0]*(len(word1)+1) for _ in range(len(word2) + 1)] for i in range(1,len(word1) + 1): dp[0][i] += i for i in range(1,len(word2) + 1): dp[i][0] += i for i in range(1, len(word2) + 1): for j in range(1, len(word1) + 1): if word2[i-1] == word1[j - 1]: dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]-1) + 1 else: dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) + 1 return dp[-1][-1]
classSolution(object): defnumIslands(self, grid): """ :type grid: List[List[str]] :rtype: int""" if grid == []: return0 res = 0 defdfs(grid,pox,poy): xh = [1,0,-1,0] yh = [0,1,0,-1] for k in range(4): x = xh[k] + pox y = yh[k] + poy if0 <= x < len(grid) and0 <= y < len(grid[0]) and grid[x][y] == '1': grid[x][y] = '-1' dfs(grid,x,y) for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '1': res += 1 grid[i][j] = '-1' dfs(grid,i,j) return res
classSolution(object): deffindKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int""" defquick_sort(nums,left,right): if left >= right: return pivot = nums[left] l = left r = right while l < r: while l < r and nums[r] > pivot: r -= 1 while l < r and nums[l] <= pivot: l += 1 nums[l],nums[r] = nums[r],nums[l] nums[left],nums[l] = nums[l],nums[left] quick_sort(nums,left,l-1) quick_sort(nums,l+1,right) quick_sort(nums,0,len(nums)-1) return nums[-k]
classSolution(object): deffindKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int""" # 堆 # 构造大根树 defcreate_heap(nums,root_index,n): left = root_index*2 + 1 right = root_index*2 + 2 max_index = root_index if left <= n and nums[root_index] < nums[left]: max_index = left if right <= n and nums[max_index] < nums[right]: max_index = right if max_index != root_index: nums[max_index],nums[root_index] = nums[root_index],nums[max_index] create_heap(nums,max_index,n)
defsort_heap(nums): n = len(nums) - 1 last_index = (n-1)//2# 2i+1,2i+2 for i in range(last_index+1)[::-1]: create_heap(nums,i,n) sort_heap(nums) n = len(nums) - 1 for i in range(k): nums[0],nums[n-i] = nums[n-i],nums[0] create_heap(nums,0,n-i-1) return nums[-k]
classSolution(object): deffindMin(self, nums): """ :type nums: List[int] :rtype: int """ left = 0 right = len(nums) - 1 while left < right: mid = (left + right) >> 1 if nums[mid] > nums[right]: left = mid + 1 elif nums[mid] < nums[right]: right = mid else: right -= 1 return nums[left]
无重复字符串的最长子串
list,维护最长子串,复杂度较高
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): deflengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if s == '': return0 res = [] ans = 0 for val in s: while val in res: res.pop(0) res.append(val) ans = max(ans,len(res)) return ans
使用set代替list,加快查找和删除的效率,用一个循环模拟set中元素的位置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): deflengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ occ = set() ans = 0 right = -1 n = len(s) for left in range(len(s)): if left != 0: occ.remove(s[left-1]) while right + 1 < n and s[right + 1] notin occ: occ.add(s[right + 1]) right += 1 ans = max(ans, right - left + 1) return ans
classSolution(object): deflengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ mapper = {} left,right = 0,0 n = len(s) ans = 0 while right < n: if s[right] notin mapper: mapper[s[right]] = right else: ans = max(ans, right - 1 - left + 1) if mapper[s[right]] >= left: left = mapper[s[right]] + 1 mapper[s[right]] = right right += 1 ans = max(ans,right -1 - left + 1) return ans
classSolution(object): deflengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int""" if nums == []: return0 dp = [nums[0]] for i in range(1,len(nums)): val = nums[i] if val > dp[-1]: dp.append(val) else: left = 0 right = len(dp) - 1 pos = right while left <= right: mid = (left + right) >> 1 if dp[mid] >= val: pos = mid right = mid - 1 else: left = mid + 1 dp[pos] = val return len(dp)
classSolution(object): defmySqrt(self, x): """ :type x: int :rtype: int """ if x < 2: return x left = 0 right = x//2 while left <= right: mid = (left + right) >> 1 if mid*mid == x: return mid if mid*mid > x: right = mid - 1 elif (mid+1)**2 >x: return mid else: left = mid + 1 return left
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution(object): defzigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root == None: return [] ans = [] res = [] queue = [root] flag = 0 level = 1 while queue: node = queue.pop(0) level -= 1 res.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) if level == 0: if flag == 1: res = res[::-1] flag ^= 1 level = len(queue) ans.append(res) res = [] return ans
classSolution(object): defmergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if lists == []: returnNone lists = [val for val in lists if val != None ] defcreate_heap(lists,root_index,n): left = 2 * root_index + 1 right = 2 * root_index + 2 min_index = root_index if left <= n and lists[left].val < lists[min_index].val: min_index = left if right <= n and lists[right].val < lists[min_index].val: min_index = right if min_index != root_index: lists[min_index],lists[root_index] = lists[root_index],lists[min_index] create_heap(lists,min_index,n) defsort_heap(lists): n = len(lists) - 1 last_index = (n-1)//2 for i in range(last_index + 1)[::-1]: create_heap(lists,i,n) sort_heap(lists) dummy = ListNode(-1) cur = dummy while lists: n = len(lists) - 1 if n == 0: cur.next = lists[0] break cur.next = ListNode(lists[0].val) cur = cur.next lists[0] = lists[0].next if lists[0] == None: lists[0] = lists[-1] lists.pop() create_heap(lists,0,len(lists) - 1) return dummy.next
二叉树最近公共祖先
236,后序遍历,一旦遇到选定子阶段就返回,不需要往下再遍历了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): deflowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""" if root == q or root == p or root == None: return root left = self.lowestCommonAncestor(root.left,p,q) right = self.lowestCommonAncestor(root.right,p,q) if left and right: return root elif left == None: return right else: return left
classSolution(object): defmaxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ if grid == []: return0 visits = [[0]*len(grid[0]) for _ in range(len(grid))] defdfs(grid,visits,pox,poy,res): xh = [1,0,-1,0] yh = [0,1,0,-1] for i in range(4): x = xh[i] + pox y = yh[i] + poy if0 <= x < len(grid) and0 <= y < len(grid[0]) and visits[x][y] == 0and grid[x][y] == 1: visits[x][y] = 1 res[0] += 1 dfs(grid,visits,x,y,res) ans = 0 res = [0] for i in range(len(grid)): for j in range(len(grid[0])): if visits[i][j] == 0and grid[i][j] == 1: res[0] += 1 visits[i][j] = 1 dfs(grid,visits,i,j,res) ans = max(res[0],ans) res[0] = 0 return ans
classSolution(object): defmaximalSquare(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if matrix == []: return0 side = 0 dp = [[0]*len(matrix[0]) for _ in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == '1': if i == 0or j == 0: dp[i][j] = 1 else: dp[i][j] = min(dp[i-1][j-1],min(dp[i][j-1],dp[i-1][j])) + 1 side = max(side,dp[i][j]) return side ** 2
classSolution(object): defmaxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int]""" if nums == []: return [] ans = [] stack = [] # 单调栈 for i in range(len(nums)): while stack and stack[0] < i - k + 1: stack.pop(0) while stack and nums[stack[-1]] <= nums[i]: stack.pop() stack.append(i) if i >= k - 1: ans.append(nums[stack[0]]) return ans
classSolution(object): defthreeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) < 3: return [] nums = sorted(nums) res = [] for i in range(len(nums)): if i > 0and nums[i] == nums[i-1]: continue target = - nums[i] left = i + 1 right = len(nums) - 1 while left < right: if left > i+1and nums[left] == nums[left - 1]: left += 1 continue if right < len(nums) - 1and nums[right] == nums[right + 1]: right -= 1 continue if target == nums[left] + nums[right]: res.append([-target,nums[left],nums[right]]) left += 1 right -= 1 elif target < nums[left] + nums[right]: right -= 1 else: left += 1 return res
classSolution(object): defreverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode""" if head == Noneor k == 1: return head dummy = ListNode(-1) dummy.next = head cur = dummy defconvert(begin,end): dummy = ListNode(-1) dummy.next = begin pre = dummy cur = begin while cur != end: tmp = cur.next cur.next = pre pre = cur cur = tmp cur.next = pre return end,begin while cur: end = cur for i in range(k): if end.next == None: return dummy.next end = end.next # print(end) last = end.next sub_begin,sub_end = convert(cur.next,end) cur.next = sub_begin sub_end.next = last cur = sub_end return dummy.next
classSolution(object): defmaxProduct(self, nums): """ :type nums: List[int] :rtype: int""" import sys ans = -sys.maxsize if nums == []: return0 imax,imin = 1,1 for val in nums: if val < 0: imax,imin = imin,imax imax = max(val,val*imax) imin = min(val,val*imin) ans = max(ans,imax) return ans
64 最小路径和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defminPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int""" if grid == [] or grid[0] == []: return0 for i in range(1,len(grid[0])): grid[0][i] += grid[0][i-1] for j in range(1,len(grid)): grid[j][0] += grid[j-1][0] for i in range(1,len(grid)): for j in range(1,len(grid[0])): grid[i][j] = min(grid[i-1][j],grid[i][j-1]) + grid[i][j] return grid[-1][-1]
classSolution(object): defreverseBetween(self, head, left, right): """ :type head: ListNode :type left: int :type right: int :rtype: ListNode """ dummy = ListNode(-1) dummy.next = head pre = dummy cur = pre begin = dummy while left: cur = cur.next left -= 1 if left == 1: begin = cur end = cur cur = dummy while right: cur = cur.next right -= 1 last = cur.next cur = begin.next pre = begin while cur != last: tmp = cur.next cur.next = pre pre = cur cur = tmp begin.next = pre end.next = last return dummy.next
400. 第N位数字
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): deffindNthDigit(self, n): """ :type n: int :rtype: int """ count = 1 lens = 1 while n > 9 *count * lens: n -= 9 *count * lens count *= 10 lens += 1 cur_num = (n-1) / lens + count return int(str(cur_num)[(n-1)%lens])
139. 单词拆分
判断字符串能否由一个单词列表组成,思路是使用动态规划,s每个位置判断if dp[j] and s[j:i] in dicts,如果为真,则可以由单词表组成。
classSolution(object): defwordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: bool """ if s == '': returnFalse n = len(s) dp = [False]*(n+1) dp[0] = True dicts = {} for val in wordDict: dicts[val] = 1 for i in range(1,n+1): for j in range(i): if dp[j] and s[j:i] in dicts: dp[i] = True break return dp[-1]
classSolution(object): defmaxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if prices == []: return0 mins = prices[0] res = 0 for i in range(1,len(prices)): res = max(res,prices[i] - mins) mins = min(mins,prices[i]) return res
classCodec: defserialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root == None: return'' ans = '' res = [] queue = [root] while queue: node = queue.pop(0) if node: res.append(str(node.val)) else: res.append('null') continue queue.append(node.left) queue.append(node.right) ans = ','.join(res) return ans defdeserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == '': return [] res = data.split(',') root = TreeNode(int(res[0])) res.pop(0) queue = [root] while queue: node = queue.pop(0) if res[0] == 'null': node.left = None else: node.left = TreeNode(int(res[0])) queue.append(node.left) res.pop(0) if res[0] == 'null': node.right = None else: node.right = TreeNode(int(res[0])) queue.append(node.right) res.pop(0) return root
接雨水
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): deftrap(self, height): """ :type height: List[int] :rtype: int""" if height == []: return0 left = [0] * len(height) left[0] = height[0] right = [0] * len(height) right[-1] = height[-1] for i in range(1,len(height)): left[i] = (max(left[i-1],height[i])) for i in range(len(height)-1)[::-1]: right[i] = (max(right[i+1],height[i])) ans = 0 for i in range(len(height)): ans += min(right[i],left[i]) - height[i] return ans
209. 长度最小的子数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defminSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ if nums == []: return [] res = [] ans = 0 for i in range(len(nums)): res.append(nums[i]) while sum(res) >= s: if len(res) < ans or ans == 0: ans = len(res) res.pop(0) # print(res) return ans
classSolution(object): defremoveNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if head == None: returnNone dummy = ListNode(-1) dummy.next = head first = dummy for _ in range(n): first = first.next cur = dummy while first.next: cur = cur.next first = first.next cur.next =cur.next.next return dummy.next
classSolution(object): defdecodeString(self, s): """ :type s: str :rtype: str """ if s == '': return'' stack = [] i = 0 while i < len(s): if'0' <= s[i] <= '9': res = 0 while i < len(s) and'0' <= s[i] <= '9': res = res * 10 + int(s[i]) i += 1 stack.append(res) elif s[i] == ']': word = '' while stack[-1] != '[': word += stack.pop() stack.pop() num = stack.pop() # word = word[::-1] stack.append(num*word) i += 1 else: stack.append(s[i]) i += 1 # print(stack) return''.join([val[::-1] for val in stack])
206. 翻转链表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defreverseList(self, head): """ :type head: ListNode :rtype: ListNode""" if head == None: return head pre = head cur = pre.next head.next = None while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre
classSolution(object): deffindNumberOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if nums == []: return0 max_len = 0 cnt = [1] * len(nums) dp = [1] * len(nums) ans = 0 for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: if dp[i] < dp[j] + 1: dp[i] = dp[j] + 1 cnt[i] = cnt[j] elif dp[i] == dp[j] + 1: cnt[i] += cnt[j] if dp[i] > max_len: max_len = dp[i] ans = cnt[i] elif dp[i] == max_len: ans += cnt[i] return ans
96. 不同的二叉搜索树
左子树和右子树的笛卡尔积。
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): defnumTrees(self, n): """ :type n: int :rtype: int""" G = [0]*(n+1) G[0],G[1] = 1,1 for i in range(2,n+1): for j in range(1,i+1): G[i] += G[j-1]*G[i-j] return G[-1]
classSolution(object): defsortList(self, head): """ :type head: ListNode :rtype: ListNode""" defsort_func(head,tail): ifnot head: return head if head.next == tail: head.next = None return head fast = head slow = head while fast != tail: slow = slow.next fast = fast.next if fast != tail: fast = fast.next mid = slow return merge(sort_func(head,mid),sort_func(mid,tail)) defmerge(temp1,temp2): dummy = ListNode(-1) cur = dummy while temp1 and temp2: if temp1.val <= temp2.val: cur.next = temp1 temp1 = temp1.next else: cur.next = temp2 temp2 = temp2.next cur = cur.next if temp1: cur.next = temp1 else: cur.next = temp2 return dummy.next return sort_func(head,None)
41. 缺失的第一个正数
申请一个辅助数组,遍历数组填充到dp的不同位置上,找到第一个未出现的正数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): deffirstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int""" if nums == []: return1 dp = [0]*(len(nums) + 1) for val in nums: if val <= 0or val > len(nums): continue else: dp[val] = 1 for i in range(1,len(nums) + 1): if dp[i] == 0: return i return len(nums) + 1
53. 最大子数组和
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): defmaxSubArray(self, nums): """ :type nums: List[int] :rtype: int""" ans = 0 dp = ans = -sys.maxsize for val in nums: dp = max(dp,0) + val ans = max(ans,dp) return ans
1143. 最长公共子序列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): deflongestCommonSubsequence(self, text1, text2): """ :type text1: str :type text2: str :rtype: int """ if text1 == ''or text2 == '': return0 dp = [[0]*(len(text1)+1) for _ in range(len(text2)+1)] dp[0][0] = 0 for i in range(1,len(text2)+1): for j in range(1,len(text1)+1): 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]
509. 斐波那契数
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): deffib(self, N): """ :type N: int :rtype: int""" if N <= 1: return N a,b = 0,1 for i in range(2,N+1): a,b = b, a + b return b
470. 用rand7实现rand10
1 2 3 4 5 6 7 8 9 10 11 12
classSolution(object): defrand10(self): """ :rtype: int """ col,row,idx = 0,0,0 whileTrue: col = rand7() row = rand7() idx = col + (row - 1)*7 if idx <= 40: return1 + (idx - 1)%10
classSolution(object): defreorderList(self, head): """ :type head: ListNode :rtype: None Do not return anything, modify head in-place instead. """ if head == Noneor head.next == None: return head fast = head.next slow = head while fast != None: fast = fast.next slow = slow.next if fast!=None: fast = fast.next mid = slow pre = mid cur = mid.next mid.next = None while cur != None: tmp = cur.next cur.next = pre pre = cur cur = tmp dummy = ListNode(-1) p1 = head p2 = pre flag = 1 cur = dummy while p1 != p2: if flag == 1: cur.next = p1 p1 = p1.next else: cur.next = p2 p2 = p2.next flag ^= 1 cur = cur.next cur.next = p2 return dummy.next
classSolution(object): defclimbStairs(self, n): """ :type n: int :rtype: int""" if n == 0: return0 a,b = 0,1 for i in range(1,n+1): a,b = b, b+a return b
classSolution(object): defisValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if root == None: returnTrue ans = [] queue = [] cur = root while cur or queue: while cur: queue.append(cur) cur = cur.left cur = queue.pop() ans.append(cur.val) if len(ans) >= 2: if ans[-1] <= ans[-2]: returnFalse cur = cur.right returnTrue
classSolution(object): defspiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int]""" if matrix == [] or matrix[0] == []: return [] startx,starty = 0,0 endx,endy = len(matrix)-1,len(matrix[0])-1 res = [] while startx <= endx and starty <= endy: for i in range(starty,endy+1): res.append(matrix[startx][i]) startx += 1 if startx > endx: break for i in range(startx,endx+1): res.append(matrix[i][endy]) endy -= 1 if starty > endy: break for i in range(starty,endy+1)[::-1]: res.append(matrix[endx][i]) endx -= 1 if startx > endx: break for i in range(startx,endx+1)[::-1]: res.append(matrix[i][starty]) starty += 1 # print(startx,starty,endx,endy) return res
334. 递增的三元子序列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defincreasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool""" if len(nums) < 3: returnFalse sub = [nums[0]] for val in nums[1:]: if val > sub[-1]: sub.append(val) else: for j in range(len(sub)): if sub[j] >= val: sub[j] = val break if len(sub) == 3: returnTrue returnFalse
84. 柱状图中最大的矩阵
使用单调栈来求解。栈用来记录元素的下标。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): deflargestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int""" if heights == []: return0 stack = [-1] res = 0 for i in range(len(heights)): while len(stack) > 1and heights[i] <= heights[stack[-1]]: res = max(res,heights[stack.pop()]*(i-stack[-1]-1)) stack.append(i) while len(stack) > 1: res = max(res,heights[stack.pop()] * (len(heights) - stack[-1] - 1)) return res
1. 两数之和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): deftwoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if nums == []: return [] dicts = {} for i in range(len(nums)): if nums[i] in dicts: return [dicts[nums[i]],i] else: dicts[target - nums[i]] = i
279. 完全平方数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defnumSquares(self, n): """ :type n: int :rtype: int """ if n == 0: return0 dp = [0]*(n+1) for i in range(n+1): dp[i] = i y = 0 while i - y*y >= 0: dp[i] = min(dp[i],dp[i-y*y] + 1) y += 1 return dp[-1]
50. Pow(x,n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): defmyPow(self, x, n): """ :type x: float :type n: int :rtype: float""" defdfs(x,n): if n == 0: return1.0 half = dfs(x,n//2) if n % 2 == 0: return half*half else: return half*half*x if n < 0: x = 1/x n = -n return dfs(x,n)
560. 和为k的子数组
前缀和 + map求解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defsubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ pre = 0 count = 0 mp = {0:1} for val in nums: pre += val if pre - k in mp: count += mp[pre-k] if pre in mp: mp[pre] += 1 else: mp[pre] = 1 return count
classSolution(object): defsolveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ res = [] arr = [['.']*n for _ in range(n)]
defis_vaild(arr,x,y): if'Q'in arr[x]: returnFalse for i in range(len(arr)): if arr[i][y] == 'Q': returnFalse pox,poy = x,y while0 <= pox and0 <= poy: if arr[pox][poy] == 'Q': returnFalse pox -= 1 poy -= 1 pox,poy = x,y while pox < len(arr) and poy < len(arr[0]): if arr[pox][poy] == 'Q': returnFalse pox += 1 poy += 1 pox,poy = x,y while0 <= pox and poy < len(arr[0]): if arr[pox][poy] == 'Q': returnFalse pox -= 1 poy += 1 pox,poy = x,y while pox < len(arr) and0 <= poy: if arr[pox][poy] == 'Q': returnFalse pox += 1 poy -= 1 returnTrue
defdfs(arr,row,res): if row == len(arr): tmp = [] for i in range(len(arr)): tmp.append(''.join(arr[i])) res.append(tmp[::]) return for i in range(n): if is_vaild(arr,row,i): arr[row][i] = 'Q' dfs(arr,row+1,res) arr[row][i] = '.' dfs(arr,0,res) return res
盛最多水的容器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defmaxArea(self, height): """ :type height: List[int] :rtype: int""" if height == []: return0 left,right = 0,len(height) - 1 res = 0 while left < right: res = max(res,(right-left)*min(height[right],height[left])) if height[right] > height[left]: left += 1 else: right -= 1 return res
classSolution(object): defreversePairs(self, nums): """ :type nums: List[int] :rtype: int""" self.ans = 0 defdfs(nums,left,right): if right - left < 1: return mid = (left + right) // 2 dfs(nums,left,mid) dfs(nums,mid + 1, right) tmp = [] l = left r = mid + 1 while l <= mid and r <= right: if nums[l] > nums[r]: self.ans += mid - l + 1 tmp.append(nums[r]) r += 1 else: tmp.append(nums[l]) l += 1 if l <= mid: tmp.extend(nums[l:mid+1]) elif r <= right: tmp.extend(nums[r:right+1]) nums[left:right+1] = tmp dfs(nums,0,len(nums)-1) return self.ans
141.环形链表
使用快慢指针来求解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): defhasCycle(self, head): """ :type head: ListNode :rtype: bool""" if head == None: returnFalse slow = head fast = head.next while slow and fast: if slow == fast: returnTrue slow = slow.next fast = fast.next if fast: fast = fast.next returnFalse
classSolution(object): defdetectCycle(self, head): """ :type head: ListNode :rtype: ListNode""" if head == None: returnNone dummy = ListNode(-1) dummy.next = head slow = head fast = head.next while slow and fast: if slow == fast: break slow = slow.next fast = fast.next if fast: fast = fast.next if slow == Noneor fast == None: returnNone # print(slow.val,fast.val) fast = dummy while slow != fast: slow = slow.next fast = fast.next return slow
classSolution(object): defisValid(self, s): """ :type s: str :rtype: bool """ if s == '': returnTrue stack = [] for val in s: if val in'{[(': stack.append(val) else: if stack == []: returnFalse elif val == '}': if stack.pop() != '{': returnFalse elif val == ']': if stack.pop() != '[': returnFalse elif val == ')': if stack.pop() != '(': returnFalse else: returnFalse if stack: returnFalse returnTrue
classSolution(object): definorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ cur = root queue = [] ans = [] while cur or queue: while cur: queue.append(cur) cur = cur.left node = queue.pop() ans.append(node.val) cur = node.right return ans
defdfs(root,res): if root == None: return dfs(root.left,res) res.append(root.val) dfs(root.right,res) res = [] dfs(root,res) return res
classSolution(object): defspiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if matrix == [] or matrix[0] == []: return [] startx,starty = 0,0 endx,endy = len(matrix),len(matrix[0]) ans = [] while startx < endx and starty <endy: for i in range(starty,endy): ans.append(matrix[startx][i]) startx += 1 if startx >= endx: break for i in range(startx,endx): ans.append(matrix[i][endy-1]) endy -= 1 if starty >= endy: break for i in range(starty,endy)[::-1]: ans.append(matrix[endx-1][i]) endx -= 1 if startx >= endx: break for i in range(startx,endx)[::-1]: ans.append(matrix[i][starty]) starty += 1 return ans
classSolution(object): defmaximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ defcal_area(heights): stack = [-1] res = 0 for i in range(len(heights)): while len(stack) > 1and heights[i] <= heights[stack[-1]]: res = max(res,heights[stack.pop()] * (i - stack[-1] - 1)) stack.append(i) while len(stack) > 1: res = max(res, heights[stack.pop()]*(len(heights) - stack[-1] - 1)) return res if matrix == [] or matrix[0] == []: return0 nums = [0] * len(matrix[0]) ans = 0 for val in matrix: for i in range(len(val)): if int(val[i]) == 0: nums[i] = 0 else: nums[i] += int(val[i]) ans = max(ans,cal_area(nums)) return ans
classSolution(object): deftriangleNumber(self, nums): """ :type nums: List[int] :rtype: int """ if nums == 0: return0 res = 0 nums = sorted(nums) for right in range(2,len(nums)): left = 0 cur = right - 1 while left < cur: if nums[left] + nums[cur] > nums[right]: res += cur - left cur -= 1 else: left += 1 return res
62.不同路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defuniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ dp = [[0]*n for _ in range(m)] dp[0] = [1]*n for i in range(m): dp[i][0] = 1 for i in range(1,m): for j in range(1,n): dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[-1][-1]
337. 打家劫舍
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defrob(self, root): """ :type root: TreeNode :rtype: int """ defdfs(root): if root == None: return0,0 left = dfs(root.left) right = dfs(root.right) result = [0,0] # 不抢或抢 result[0] = max(left) + max(right) result[1] = left[0] + right[0] + root.val return result return max(dfs(root))
1031. 两个非重叠子数组的最大和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): defmaxSumTwoNoOverlap(self, nums, firstLen, secondLen): """ :type nums: List[int] :type firstLen: int :type secondLen: int :rtype: int """ if nums == []: return0 for i in range(1,len(nums)): nums[i] += nums[i-1] res,lmax,mmax = nums[firstLen+secondLen-1],nums[firstLen-1],nums[secondLen-1] for i in range(firstLen+secondLen,len(nums)): lmax = max(lmax,nums[i-secondLen] - nums[i-firstLen-secondLen]) mmax = max(mmax, nums[i-firstLen] - nums[i-firstLen-secondLen]) res = max(res, max(lmax + nums[i] - nums[i-secondLen],mmax + nums[i] - nums[i-firstLen])) return res
22. 括号生成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): defgenerateParenthesis(self, n): """ :type n: int :rtype: List[str] """ self.ans = [] defdfs(n,res,right): if len(res) == n*2: if right == 0: self.ans.append(res[::]) return if right > n or right < 0: return dfs(n,res + '(',right + 1) dfs(n,res + ')',right - 1) dfs(n,'',0) return self.ans
classSolution(object): defcalculate(self, s): """ :type s: str :rtype: int """ res = 0 flag = 1 stack = [] num = 0 for c in s: if c.isdigit(): num = num*10 + int(c) elif c == '+': res += num*flag num = 0 flag = 1 elif c == '-': res += num*flag num = 0 flag = -1 elif c == '(': stack.append(res) stack.append(flag) flag = 1 res = 0 elif c == ')': res += num*flag num = 0 res = stack.pop()*res + stack.pop() res += flag*num return res
classSolution(object): defmultiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ m = len(num1) n = len(num2) if num1 == '0'or num2 == '0': return'0' res = [0]*(n+m) for i in range(m)[::-1]: for j in range(n)[::-1]: val = int(num1[i])*int(num2[j]) res[i+j+1] += val for i in range(1,len(res))[::-1]: res[i-1] += res[i] // 10 res[i] = res[i] % 10 res = ''.join([str(c) for c in res]) if res[0] == '0': res = res[1:] return res
classSolution(object): defsetZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ col = set() row = set() for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: if i notin col: col.add(i) if j notin row: row.add(j) for cc in col: for i in range(len(matrix[0])): matrix[cc][i] = 0 for cc in row: for i in range(len(matrix)): matrix[i][cc] = 0
classSolution(object): deffindNumberIn2DArray(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if matrix == [] or matrix[0] == []: returnFalse x = len(matrix) - 1 y = 0 while x >= 0and y < len(matrix[0]): if matrix[x][y] == target: returnTrue elif matrix[x][y] < target: y += 1 else: x -= 1 returnFalse
defget(self, key): """ :type key: int :rtype: int """ if key notin self.stack: return-1 else: self.order.remove(key) self.order.append(key) return self.stack[key]
defput(self, key, value): """ :type key: int :type value: int :rtype: None """ if key in self.stack: self.stack[key] = value self.order.remove(key) self.order.append(key) else: if len(self.order) == self.capacity: val = self.order.pop(0) del self.stack[val] self.stack[key] = value self.order.append(key)
classSolution(object): deffindMin(self, nums): """ :type nums: List[int] :rtype: int""" if nums == []: return-1 left = 0 right = len(nums) - 1 while left < right: mid = (left + right) >> 1 if nums[mid] > nums[right]: left = mid + 1 else: right = mid return nums[left] # 寻找最大值 classSolution(object): deffindMin(self, nums): """ :type nums: List[int] :rtype: int""" left = 0 right = len(nums) - 1 while left < right: mid = (left + right) >> 1 if nums[mid] > nums[left]: left = mid else: right = mid - 1 return nums[left]
122. 买卖股票最佳时期
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defmaxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if prices == []: return0 res = 0 top = prices[0] for val in prices[1:]: if val - top > 0: res += val - top top = val return res
classSolution(object): defsumNumbers(self, root): """ :type root: TreeNode :rtype: int """ res = [] ans = [] defdfs(root,res): if root == None: return elif root.left == Noneand root.right == None: res.append(root.val) ans.append(int(''.join([str(i) for i in res]))) res.pop() return dfs(root.left,res + [root.val]) dfs(root.right,res + [root.val]) dfs(root,res) # print(ans) return sum(ans)
179. 最大数
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): deflargestNumber(self, nums): """ :type nums: List[int] :rtype: str """ classcompare(str): def__lt__(x,y): return x + y > y + x res = ''.join(sorted(map(str,nums),key = compare)) return'0'if res[0] == '0'else res
48. 旋转数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): defrotate(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ if matrix == [] or matrix[0] == []: return matrix begin = 0 end = len(matrix) - 1 while begin < end: matrix[begin],matrix[end] = matrix[end],matrix[begin] begin += 1 end -= 1 for i in range(len(matrix)): for j in range(i+1,len(matrix[0])): matrix[i][j],matrix[j][i] = matrix[j][i],matrix[i][j] return matrix
classSolution(object): defaddStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ if len(num2) > len(num1): num1,num2 = num2,num1 cur = 0 res = '' step = 0 num1 = num1[::-1] num2 = num2[::-1] while cur < len(num2): val = int(num1[cur]) + int(num2[cur]) + step step = val // 10 val = val % 10 res += str(val) cur += 1 if step == 0: res += num1[cur:] else: while cur < len(num1): val = int(num1[cur]) + step step = val // 10 val = val % 10 cur += 1 res += str(val) if step == 1: res += '1' return res[::-1]
classSolution(object): defsortArray(self, nums): """ :type nums: List[int] :rtype: List[int] """ # 快排 defquick_sort(nums,left,right): if left >= right: return index = random.randint(left, right) nums[left],nums[index] = nums[index],nums[left] pivot = nums[left] l = left r = right while left < right: while left < right and nums[right] >= pivot: right -= 1 while left < right and nums[left] <= pivot: left += 1 nums[left],nums[right] = nums[right],nums[left] nums[l],nums[left] = nums[left],nums[l] quick_sort(nums,l,left-1) quick_sort(nums,left+1,r) quick_sort(nums,0,len(nums)-1) return nums # 堆排序 defcreate_heap(nums,root_index,total_index): c1 = root_index * 2 + 1 c2 = root_index * 2 + 2 max_index = root_index if c1 <= total_index and nums[c1] > nums[max_index]: max_index = c1 if c2 <= total_index and nums[c2] > nums[max_index]: max_index = c2 if max_index != root_index: nums[max_index],nums[root_index] = nums[root_index],nums[max_index] create_heap(nums,max_index,total_index) defsort_heap(nums): n = len(nums) - 1 last_index = (n-1) // 2 for i in range(last_index + 1)[::-1]: create_heap(nums,i,n) sort_heap(nums) for i in range(len(nums))[::-1]: nums[0],nums[i] = nums[i],nums[0] create_heap(nums,0,i-1) return nums
classSolution(object): defisBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if root ==None: returnTrue self.ans = True defdfs(root): if self.ans == False: return0 if root == None: return0 left = dfs(root.left) right = dfs(root.right) if abs(left - right) > 1: self.ans = False return0 return max(left,right) + 1 dfs(root) return self.ans
739. 每日温度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): defdailyTemperatures(self, T): """ :type T: List[int] :rtype: List[int] """ if T == []: return [] ans = [0]*len(T) stack = [] for i in range(len(T)): t = T[i] while stack and t > T[stack[-1]]: day = stack.pop() ans[day] = i - day stack.append(i) return ans
classSolution(object): defcanFinish(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ if numCourses == 0: returnTrue preccourse = {} for course in prerequisites: if course[1] notin preccourse: preccourse[course[1]] = [course[0]] else: preccourse[course[1]].append(course[0]) visit = [0]*numCourses self.vaild = True defdfs(u): visit[u] = 1 if u in preccourse: for v in preccourse[u]: if visit[v] == 0: dfs(v) ifnot self.vaild: return elif visit[v] == 1: self.vaild = False return visit[u] = 2 for i in range(numCourses): if self.vaild and visit[i] == 0: dfs(i) return self.vaild
classSolution(object): defjump(self, nums): """ :type nums: List[int] :rtype: int""" if len(nums) <= 1: return0 right = nums[0] left = 0 new_right = right res = 1 while left < len(nums): if left < right: left += 1 if left == len(nums)-1: return res new_right = max(new_right, left + nums[left]) else: if right > new_right: return-1 right = new_right res += 1 return res
classSolution(object): defminWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ if s == ''or t == '': return'' if len(t) > len(s): return'' window = {} res = '' for c in t: window[c] = 0 upper = {} for c in t: if c notin upper: upper[c] = 1 else: upper[c] += 1 left = right = 0 count = 0 while right < len(s): if s[right] in window: window[s[right]] += 1 if window[s[right]] == upper[s[right]] or (upper[s[right]] > 1and window[s[right]] < upper[s[right]]): count += 1 while count >= len(t): if res ==''or len(res) > right - left + 1: res = s[left:right+1] if s[left] in window: window[s[left]] -= 1 if window[s[left]] < upper[s[left]]: count -= 1 left += 1 right += 1
classSolution(object): defmajorityElement(self, nums): """ :type nums: List[int] :rtype: int """ if nums == []: return-1 count = 1 candidate = nums[0] for val in nums[1:]: if count == 0: candidate = val count +=1 else: if val == candidate: count += 1 else: count -= 1 return candidate ## 随机生成上述数组 import random res = [] val = random.randint(0,10) res.extend([val] * (len(nums)//2+1)) rr = 0 for i in range(len(nums)//2): rr = random.randint(0,10) while rr == val: rr = random.randint(0,10) res.append(rr) random.shuffle(res)
python中随机数的用法
1 2 3 4 5 6 7
import random val = random.random() # 0.654567822 val = random.randint(0,10) # 8 random.choice('tomorrow') # r,随机取一个 random.uniform(1.1,5.4) # 2.2332123 random.randrange(1,100,2) # 55, 随机选一个,间隔为2,全是奇数 random.shuffle(a)
classSolution: defminMeetingRooms(self,intervals): intervals.sort() # 开始时间排序 heap = [] ans = 0 for begin,end in intervals: while heap and heap[-1] <= left: heapq.heappop(heap) heapq.heappush(heap,end) ans = min(ans,len(heap)) return ans
56. 合并区间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): defmerge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ if intervals == []: return [] ans = [] intervals.sort() for left,right in intervals: if ans != [] and ans[-1][-1] < left: ans.append([left,max(ans[-1][-1],right)]) elif ans == []: ans.append([left,right]) else: ans[-1][-1] = max(ans[-1][-1],right) return ans
零钱兑换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defcoinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ if coins == []: return0 dp = [sys.maxsize]*(amount + 1) dp[0] = 0 for coin in coins: for i in range(coin,amount + 1): dp[i] = min(dp[i],dp[i-coin] + 1) return dp[-1] if dp[-1] != sys.maxsize else-1
523. 连续子数组和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defcheckSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ if len(nums) < 2: returnFalse res = 0 m = {0:-1} for i in range(len(nums)): res = (res + nums[i]) % k if res in m: if i - m[res] >= 2: returnTrue else: m[res] = i returnFalse
151. 颠倒字符串中的单词
1 2 3 4 5 6 7
classSolution(object): defreverseWords(self, s): """ :type s: str :rtype: str """ return' '.join([val for val in s.strip().split(' ') if val != ''][::-1])
413. 等差数列划分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defnumberOfArithmeticSlices(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n < 2: return0 d,t = nums[1] - nums[0],0 ans = 0 for i in range(2,len(nums)): if nums[i] - nums[i-1] == d: t += 1 else: d = nums[i] - nums[i-1] t = 0 ans += t return ans
classSolution(object): deflongestPalindrome(self, s): """ :type s: str :rtype: str """ if s == '': return'' ans = '' res = '' for i in range(len(s)): # jishu left = i right = i res = '' while left >= 0and right < len(s) and s[left] == s[right]: left -= 1 right += 1 res = s[left+1:right] if len(ans) < len(res): ans = res res = '' # oushu left = i-1 right = i while left >= 0and right < len(s) and s[left] == s[right]: left -= 1 right += 1 res = s[left+1:right] if len(ans) < len(res): ans = res return ans
classSolution(object): deftrap(self, height): """ :type height: List[int] :rtype: int""" if height == []: return0 left = [0] * len(height) right = [0] * len(height) left[0] =height[0] for i in range(1,len(height)): left[i] = max(left[i-1],height[i]) right[-1] = height[-1] for i in range(len(height)-1)[::-1]: right[i] = max(right[i+1],height[i]) ans = 0 # print(left) # print(right) for i in range(len(height)): ans += min(left[i],right[i]) - height[i] return ans
classSolution(object): deffindKthNumber(self, n, k): """ :type n: int :type k: int :rtype: int """ defget_step(cur,n): step,first,last = 0,cur,cur while first <= n: step += min(last,n) - first + 1 first *= 10 last = last * 10 + 9 return step cur = 1 k -= 1 while k: steps = get_step(cur,n) if steps <= k: k -= steps cur += 1 else: k -= 1 cur *= 10 return cur
632. 最小区间
使用优先队列来解,保持队列长度为n。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defsmallestRange(self, nums: List[List[int]]) -> List[int]: from queue import PriorityQueue q = PriorityQueue() n = len(nums) maxx = -sys.maxsize for i in range(n): q.put((nums[i][0],i,0)) maxx = max(maxx, nums[i][0]) begin,end = -sys.maxsize,sys.maxsize while q.qsize() == n: val,i,j = q.get() if maxx - val < end - begin: begin,end = val,maxx if j+1 < len(nums[i]): nv = nums[i][j+1] q.put((nv,i,j+1)) maxx = max(nv,maxx) return [begin,end]
classSolution(object): deflongestIncreasingPath(self, matrix): """ :type matrix: List[List[int]] :rtype: int """ if matrix == [] or matrix[0] == []: return0 res = [[0]*len(matrix[0]) for _ in range(len(matrix))] defdfs(res,matrix,pox,poy): if res[pox][poy] != 0: return res[pox][poy] xh = [0,1,0,-1] yh = [1,0,-1,0] for i in range(4): px = pox + xh[i] py = poy + yh[i] if0 <= px < len(matrix) and0 <= py < len(matrix[0]) and matrix[px][py] > matrix[pox][poy]: res[pox][poy] = max(res[pox][poy], dfs(res,matrix,px,py)) res[pox][poy] += 1 return res[pox][poy] ans = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): ans = max(ans,dfs(res,matrix,i,j)) return ans
classSolution(object): defsearchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ left = 0 right = len(nums) - 1 if nums == []: return [-1,-1] while left <= right: mid = (left + right) >> 1 if nums[mid] == target: break elif nums[mid] < target: left = mid + 1 else: right = mid - 1 if left > right: return [-1,-1] left = mid right = mid while left >= 0and nums[left] == target: left -= 1 while right < len(nums) and nums[right] == target: right += 1 return [left+1,right-1]
classSolution(object): defmaxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ import sys if nums == []: return0 dp = [-sys.maxsize] *len(nums) cur = 0 for i in range(len(nums)): if cur + nums[i] > 0: cur = cur + nums[i] dp[i] = cur else: cur = max(0,nums[i]) dp[i] = nums[i] val = max(dp) return val #返回最大和所在数组 right = dp.index(val) left = right if val <= 0: print(nums[left:right+1]) return max_val while left >= 0: if val > 0: val -= nums[left] left -= 1 else: break print(nums[left+1:right+1]) return max_val
135. 分发糖果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defcandy(self, ratings): """ :type ratings: List[int] :rtype: int """ left = [1]*len(ratings) right = [1]*len(ratings) for i in range(1,len(ratings)): if ratings[i] > ratings[i-1]: left[i] = left[i-1] + 1 for i in range(len(ratings) - 1)[::-1]: if ratings[i] > ratings[i+1]: right[i] = right[i+1] + 1 ans = 0 for i in range(len(ratings)): ans += max(left[i],right[i]) return ans # 如果题目是连成一个环,那么找到最小的元素,一次向左和向右遍历,随后取max
classSolution(object): defcountDigitOne(self, n): """ :type n: int :rtype: int """ k, mulk = 0, 1 ans = 0 while n >= mulk: ans += (n // (mulk * 10)) * mulk + min(max(n % (mulk * 10) - mulk + 1, 0), mulk) k += 1 mulk *= 10 return ans
删掉字符串中所有相邻的重复项
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defremoveDuplicates(self, s): """ :type s: str :rtype: str """ stack = [] for val in s: if stack == []: stack.append(val) elif stack[-1] != val: stack.append(val) else: stack.pop() return''.join(stack)
classSolution(object): defdeleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None: return head dummy = ListNode(-1) dummy.next = head pre = dummy cur = head right = cur.next while cur: if right and cur.val == right.val: while right and cur.val == right.val: right = right.next pre.next = right cur = right if right: right = right.next elif right and cur.val != right.val: right = right.next cur = cur.next pre = pre.next else: break return dummy.next
138. 复制带随机指针的链表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): defcopyRandomList(self, head): """ :type head: Node :rtype: Node """ self.dicts = {} defdfs(head): if head == None: returnNone if head notin self.dicts: newHead = Node(head.val,None,None) self.dicts[head] = newHead newHead.next = dfs(head.next) newHead.random = dfs(head.random) return self.dicts[head] return dfs(head)
classSolution(object): defmaxNumber(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int] """ defpick(num,pick_k): pop_n = len(num) - pick_k res = [] for val in num: while pop_n and res and val > res[-1]: pop_n -= 1 res.pop() res.append(val) return res[:pick_k] defmerge(nums1,nums2): res = [] while nums1 and nums2: res.append(nums1.pop(0) if nums1 > nums2 else nums2.pop(0)) res.extend(nums1 or nums2) return res ans = 0 for i in range(k+1): if i <= len(nums1) and k-i <= len(nums2): ans = max(ans, merge(pick(nums1,i),pick(nums2,k-i))) return ans
classSolution(object): defrob(self, nums): """ :type nums: List[int] :rtype: int """ if nums == []: return0 if len(nums) <= 2: return max(nums) dp = [0] *len(nums) dp[0] = nums[0] dp[1] = max(nums[0],nums[1]) for i in range(2,len(nums)): dp[i] = max(nums[i] + dp[i-2], dp[i-1]) return dp[-1] # 计算路径 if nums == []: return0 if len(nums) <= 2: return max(nums) path = ['']*len(nums) dp = [0] *len(nums) dp[0] = nums[0] path[0] = '0' dp[1] = max(nums[0],nums[1]) if dp[1] == nums[1]: path[1] += str(1) else: path[1] += str(0) for i in range(2,len(nums)): dp[i] = max(nums[i] + dp[i-2], dp[i-1]) if dp[i] == dp[i-1]: path[i] = path[i-1] else: path[i] = path[i-2] + str(i) print(path[-1]) return dp[-1]
55. 跳跃游戏
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defcanJump(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) <= 1: returnTrue right = nums[0] cur = 1 while cur <= right: right = max(nums[cur] + cur, right) if right >= len(nums)-1: returnTrue cur += 1 returnFalse
78. 子集
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution(object): defsubsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.ans = [] defdfs(nums,pos,res): self.ans.append(res) for i in range(pos,len(nums)): dfs(nums,i+1,res + [nums[i]]) dfs(nums,0,[]) return self.ans
classSolution(object): deffourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ if len(nums) < 4: return [] ans = [] n = len(nums) nums = sorted(nums) for i in range(n-3): if i > 0and nums[i] == nums[i-1]: continue if nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target: break if nums[i] + nums[n-3] + nums[n-2] + nums[n-1] < target: continue for j in range(i + 1,n - 2): if j > i + 1and nums[j] == nums[j-1]: continue if nums[i] + nums[j] + nums[j+1] + nums[j+2] > target: break if nums[i] + nums[j] + nums[n-1] + nums[n-2] < target: continue left,right = j + 1, n - 1 while left < right: total = nums[i] + nums[j] + nums[left] + nums[right] if total == target: ans.append([nums[i], nums[j], nums[left], nums[right]]) while left < right and nums[left] == nums[left + 1]: left += 1 left += 1 while left < right and nums[right] == nums[right - 1]: right -= 1 right -= 1 elif total < target: left += 1 else: right -= 1 return ans
classSolution(object): defpostorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ # 递归 self.res = [] defdfs(root): if root == None: return dfs(root.left) dfs(root.right) self.res.append(root.val) dfs(root) return self.res # 用栈,根右左,左右根 if root == None: return [] res = [] stack = [root] while stack: node = stack.pop() res.append(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) return res[::-1] # 遍历完左边,然后遍历右边 classSolution(object): defpostorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None: return [] res = [] stack = [] prev = None while root or stack != []: while root: stack.append(root) root = root.left root = stack[-1] if root.right and root.right != prev: root = root.right else: prev = stack.pop() res.append(root.val) root = None return res
22. 链表中第k个节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defgetKthFromEnd(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ first = head for _ in range(k): first = first.next second = head while first != None: second = second.next first = first.next return second
classSolution(object): deflastRemaining(self, n, m): """ :type n: int :type m: int :rtype: int""" # 模拟法,超时了 stack = [i for i in range(n)] cur = 0 while len(stack) > 1: lens = len(stack) cur = (cur + m - 1) % lens stack.pop(cur) return stack[0] # 数学规律反推法,从最后剩下的两个数字开始,规律为 # (当前位置 + m) % 上一轮长度 # 最后一轮是1,所以上一轮从2开始 ans = 0 for i in range(2, n+1): ans = (ans + m) % i return ans
classSolution(object): defcalculate(self, s): """ :type s: str :rtype: int """ res = [] num = 0 presign = '+' for idx,val in enumerate(s): if val in'0123456789': num = num * 10 + int(val) if idx == len(s) - 1or val in'+-*/': if presign == '+': res.append(num) elif presign == '-': res.append(-num) elif presign == '*': res.append(res.pop() * num) else: res.append(int(res.pop()*1.0 / num)) presign = val num = 0 return sum(res)
718. 最长重复子数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): deffindLength(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ if nums1 == [] or nums2 == []: return0 ans = 0 dp = [[0]*(len(nums1) + 1) for _ in range(len(nums2) + 1)] dp[0][0] = 0 for i in range(1, len(nums2) + 1): for j in range(1, len(nums1) + 1): if nums2[i-1] == nums1[j-1]: dp[i][j] = dp[i-1][j-1] + 1 ans = max(dp[i][j], ans) return ans
518. 零钱兑换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defchange(self, amount, coins): """ :type amount: int :type coins: List[int] :rtype: int """ if coins == []: return0 dp = [0] * (amount + 1) dp[0] = 1 for coin in coins: for i in range(coin,amount + 1): dp[i] += dp[i - coin] return dp[-1]
54. 二叉搜索树第k大节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
defkthLargest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int5""" self.k = k self.ans = root.val defdfs(root): if root == None: return dfs(root.right) if self.k == 0: return self.k -= 1 if self.k == 0: self.ans = root.val dfs(root.left) dfs(root) return self.ans
classSolution(object): deflongestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return0 nums_s = set(nums) ans = 1 for val in nums_s: if val + 1notin nums_s: lens = 1 while val - 1in nums_s: lens += 1 val -= 1 ans = max(ans, lens) return ans
104. 二叉树最大深度
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution(object): defmaxDepth(self, root): """ :type root: TreeNode :rtype: int """ defdfs(root): if root == None: return0 left = dfs(root.left) right = dfs(root.right) return max(left,right) + 1 return dfs(root)
classSolution(object): defsuperEggDrop(self, K, N): """ :type K: int :type N: int :rtype: int """ if N == 1: return1 if K == 1: return N dp = [[0] * (K + 1) for _ in range(N + 1)] # K个蛋,最多扔N次 for i in range(1, K+1): # 只有一次机会,不论K(蛋)有几个,只要扔一次 dp[1][i] = 1 ans = -1 for i in range(2,N+1): # 机会次数 for j in range(1, K+1): # 蛋的个数 dp[i][j] = 1 + dp[i-1][j-1] + dp[i-1][j] # 蛋碎 + 蛋没碎 if dp[i][K] >= N: ans = i break return ans
classSolution(object): defisSymmetric(self, root): """ :type root: TreeNode :rtype: bool""" if root == None: returnTrue defdfs(A,B): if A == Noneand B == None: returnTrue if A == Noneor B == None: returnFalse return (A.val == B.val) and dfs(A.left,B.right) and dfs(A.right,B.left) return dfs(root.left,root.right)
classSolution(object): defisPalindrome(self, pHead): # write code here if pHead == None: returnTrue first = pHead second = pHead.next if second == None: returnTrue flag = 0 while second.next != None: first = first.next second = second.next if second.next == None: flag = 1 break second = second.next mid = first left = mid right = mid.next cur = pHead nex = cur.next while cur != mid: tmp = nex.next nex.next = cur cur = nex nex = tmp if flag == 1: left = mid.next while left and right: if left.val != right.val: returnFalse left = left.next right = right.next returnTrue
def__init__(self, num_units: int = None, activation_func = None, use_bias: bool = False, name="mlp"): super(MLP, self).__init__(name=name) self.num_units = num_units self.activation_func = activation_func self.dense_layers = [] for i in range(0, len(self.num_units)): self.dense_layers.append(tf.keras.layers.Dense(units=self.num_units[i], use_bias=use_bias, name="{}_dense_{}".format(name, i)))
defcall(self, inputs): transform_layers = [inputs] for i, layer in enumerate(self.dense_layers): next_layer = layer(transform_layers[-1]) if i != len(self.dense_layers) - 1: if self.activation_func isnotNone: next_layer = self.activation_func(next_layer) transform_layers.append(next_layer) return transform_layers[-1]
a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> c = np.tensordot(a,b, axes=([1,0],[0,1])) >>> c.shape (5, 2) >>> c array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) >>> # A slower but equivalent way of computing the same... >>> d = np.zeros((5,2)) >>> for i in range(5): ... for j in range(2): ... for k in range(3): ... for n in range(4): ... d[i,j] += a[k,n,i] * b[n,k,j] >>> c == d array([[ True, True], [ True, True], [ True, True], [ True, True], [ True, True]])
classSolution(object): defnumDistinct(self, s, t): """ :type s: str :type t: str :rtype: int """ if len(s) < len(t): return0 dp = [[0] * (len(s)+1) for _ in range(len(t) + 1)] for i in range(len(s)+1): dp[-1][i] = 1 for i in range(len(t))[::-1]: for j in range(len(s))[::-1]: if t[i] == s[j]: dp[i][j] = dp[i+1][j+1] + dp[i][j+1] else: dp[i][j] = dp[i][j+1] # print(dp) return dp[0][0]
112.路径总和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defhasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ defdfs(root,sum): if root == None: returnFalse if sum - root.val == 0and root.left == Noneand root.right==None: returnTrue return dfs(root.left,sum - root.val) or dfs(root.right, sum - root.val) if root == None: returnFalse return dfs(root,sum)
classSolution(object): defcompareVersion(self, version1, version2): """ :type version1: str :type version2: str :rtype: int """ list1 = [int(val) for val in version1.split('.')] list2 = [int(val) for val in version2.split('.')] flag = 1 if len(list1) > len(list2): list1,list2 = list2,list1 flag = -1 for i in range(len(list1)): if list1[i] > list2[i]: return flag elif list1[i] < list2[i]: return flag * -1 for i in range(len(list1),len(list2)): if list2[i] > 0: return flag * -1 return0
162. 寻找峰值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): deffindPeakElement(self, nums): """ :type nums: List[int] :rtype: int 二分,往高处走 """ import sys nums = [-sys.maxsize] + nums + [-sys.maxsize] left = 0 right = len(nums) while left < right: mid = (left + right) >> 1 if nums[mid-1] < nums[mid] and nums[mid] > nums[mid+1]: return mid - 1 if nums[mid-1] > nums[mid]: right = mid else: left = mid
classSolution(object): defcombinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ if candidates == []: return [] candidates = sorted(candidates) defdfs(candidates,target,res,pos,ans): if target == 0: if ans notin ans: ans.append(res) return if target < candidates[0]: return for i in range(pos,len(candidates)): dfs(candidates, target - candidates[i], res + [candidates[i]],i,ans) ans = [] dfs(candidates,target,[],0,ans) return ans
大数相加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): defaddStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ max_len = max(len(num1),len(num2)) num1 = num1.zfill(max_len) num2 = num2.zfill(max_len) result = [0]* (max_len + 1) for i in range(max_len)[::-1]: tmp = int(num1[i]) + int(num2[i]) + result[i+1] result[i+1] = tmp % 10 result[i] = tmp // 10 if result[0] == 0: result = result[1:] return''.join(str(val) for val in result)
classSolution(object): defmultiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ if num1 == '0'or num2 == '0': return'0' n = len(num1) m = len(num2) res = [0]*(n+m) for i in range(n): for j in range(m): res[i+j+1] += int(num1[i]) * int(num2[j]) for i in range(n+m)[::-1]: res[i-1] += res[i] // 10 res[i] = res[i] % 10 index = 0 while res[index] == 0: index += 1 return''.join(str(val) for val in res[index:])
115. 最小栈
常数时间得到栈的最小值,用一个辅助单调栈来做。
543. 二叉树的直径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defdiameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 defdfs(root): if root == None: return0 left = dfs(root.left) right = dfs(root.right) self.ans = max(self.ans,left + right + 1) return max(left,right) + 1 dfs(root) return self.ans - 1if self.ans >= 0else0
圆环回到原点
圆环上有m个点,每次可以顺时针,逆时针走,走n步回到了0有多少种情况。
1 2 3 4 5 6 7 8 9
classSolution: defbackToOrigin(self,m,n): dp = [[0] * m for _ n range(n + 1)] dp[0][0] = 1 for i in range(1,n+1): for j in range(m): dp[i][j] = dp[i-1][(j-1+m)%m] + dp[i-1][(j+1+m)%m] return dp[n][0] # dp[i][j] 表示第i步,走到j点所需的步数。
958. 二叉树的完全性检验
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): defisCompleteTree(self, root): """ :type root: TreeNode :rtype: bool """ if root == None: returnTrue nodes = [(root,1)] i = 0 while i < len(nodes): node,v = nodes[i] i += 1 if node: nodes.append((node.left,2*v)) nodes.append((node.right,2*v+1)) return nodes[-1][1] == len(nodes)
classSolution(object): deffindOrder(self, numC, pre): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int] """ graph = [[] for _ in range(numC)] # 先修课:后修课 inedge = [0]*numC # 存储节点的入度 for C,preC in pre: graph[preC].append(C) inedge[C] += 1 queue = [] res = [] for idx, course in enumerate(inedge): if course == 0: queue.append(idx) while queue: t = queue.pop(0) res.append(t) for C in graph[t]: inedge[C] -= 1 if inedge[C] == 0: queue.append(C) if len(res) == numC: return res else: return []
classSolution(object): defexist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ if word == '': returnTrue if board == [] or board[0] == []: returnFalse defdfs(board,visit,word,pox,poy): if word == '': returnTrue xh = [0,1,0,-1] yh = [1,0,-1,0] for k in range(4): x = pox + xh[k] y = poy + yh[k] if0<= x < len(board) and0<=y<len(board[0]) and visit[x][y] == 0and board[x][y] == word[0]: visit[x][y] = 1 if dfs(board,visit,word[1:],x,y): returnTrue visit[x][y] = 0 returnFalse visit = [[0] * len(board[0]) for _ in range(len(board))] for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == word[0]: visit[i][j] = 1 if dfs(board,visit,word[1:],i,j): returnTrue visit[i][j] = 0 returnFalse
classSolution(object): defremoveKdigits(self, num, k): """ :type num: str :type k: int :rtype: str """ if len(num) <= k: return'0' stack = [] for val in num: if stack == []: stack.append(val) else: while stack and val < stack[-1] and k > 0: stack.pop() k -= 1 stack.append(val) while k > 0: stack.pop() k -= 1 while stack and stack[0] == '0': stack.pop(0) return'0'if stack == [] else''.join(stack)
321. 戳气球
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution(object): defmaxCoins(self, nums): """ :type nums: List[int] :rtype: int """ nums = [1] + nums + [1] dp = [[0] * len(nums) for _ in range(len(nums))] for i in range(len(nums))[::-1]: for j in range(i+1,len(nums)): for k in range(i+1,j): dp[i][j] = max(dp[i][j],dp[i][k] + dp[k][j] + nums[i]*nums[k]*nums[j]) return dp[0][-1]
classSolution(object): defdeleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None: return head first = head second = first.next while second: while second and first.val == second.val: second = second.next first.next = second first = second if first == None: return head second = first.next return head
114. 二叉树展开为链表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution(object): defflatten(self, root): """ :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead. """ while root: if root.left == None: root = root.right else: pre = root.left while pre.right != None: pre = pre.right pre.right = root.right root.right = root.left root.left = None root = root.right
230. 二叉搜索树中第k小的元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defkthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ res = [] defdfs(root,res): if root==None: return dfs(root.left,res) res.append(root.val) dfs(root.right,res) dfs(root,res) return res[k-1]
classSolution(object): defswapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None: return head dummy = ListNode(-1) dummy.next = head first = dummy second = head while second != None: last = second.next if last == None: break first.next = last second.next = last.next last.next = second first = second second = second.next return dummy.next
classSolution(object): defmoveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ if nums == []: return cur = 0 right = 0 while right < len(nums): if nums[right] != 0: nums[cur] = nums[right] cur += 1 right += 1 else: right += 1 while cur < len(nums): nums[cur] = 0 cur += 1
classSolution(object): defvalidIPAddress(self, queryIP): """ :type queryIP: str :rtype: str """ defisIPV4(queryIP): IPList = queryIP.split('.') if len(IPList) != 4: returnFalse for val in IPList: try: if str(int(val)) != val: returnFalse except: returnFalse ifnot(0 <= int(val) <= 255): returnFalse returnTrue if isIPV4(queryIP): return'IPv4' defisIPV6(queryIP): IPList = queryIP.split(':') if len(IPList) != 8: returnFalse for val in IPList: ifnot( 1<=len(val)<=4): returnFalse for c in val: if c notin'1234567890abcdefABCDEF': returnFalse returnTrue if isIPV6(queryIP): return'IPv6' return'Neither'
classSolution(object): deffindDiagonalOrder(self, mat): """ :type mat: List[List[int]] :rtype: List[int] """ if mat == []: return [] res = [] lenx = len(mat) leny = len(mat[0]) total = 0 while total < lenx + leny: # 1,3,5,7... x = total if total < lenx else lenx - 1 y = total - x while0 <= x < lenx and0 <= y < leny: res.append(mat[x][y]) x -= 1 y += 1 total += 1 if total >= lenx + leny: return res y = total if total < leny else leny - 1 x = total - y while0 <= x < lenx and0 <= y < leny: res.append(mat[x][y]) x += 1 y -= 1 total += 1 return res
classSolution(object): defpreorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ self.res = [] defdfs(root): if root == None: return self.res.append(root.val) dfs(root.left) dfs(root.right) dfs(root) return self.res # 迭代法 if root == None: return [] res = [] queue = [] cur = root while queue or cur: while cur: queue.append(cur) res.append(cur.val) cur = cur.left cur = queue.pop() cur = cur.right return res
14. 最长公共前缀
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): deflongestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if strs == []: return'' common = strs[0] for val in strs[1:]: common = common[:len(val)] for i in range(len(val)): if i >= len(common): break if common[i] != val[i]: common = common[:i] break return common
classSolution(object): defthreeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() import sys ans = sys.maxsize for idx,val in enumerate(nums): left = idx + 1 right = len(nums) - 1 while left < right: tmp = nums[left] + nums[right] + val if abs(tmp - target) < abs(ans - target): ans = tmp if tmp - target > 0: right -= 1 else: left += 1 return ans
classSolution(object): defsearchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if matrix == []: returnFalse left = 0 right = len(matrix) - 1 while left < right: mid = (left + right) >> 1 if matrix[mid][0] > target: right = mid - 1 else: left = mid if left + 1 == right: if matrix[right][0] > target: right -= 1 else: left += 1 row = left left = 0 right = len(matrix[0]) - 1 while left <= right: mid = (left + right) >> 1 if matrix[row][mid] == target: returnTrue if matrix[row][mid] > target: right = mid - 1 else: left = mid + 1 returnFalse
classSolution(object): defshortestSubarray(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ queue = [0] for val in nums: queue.append(queue[-1] + val) indexs = [] ans = len(nums) + 1 for idx, sums in enumerate(queue): while indexs != [] and sums <= queue[indexs[-1]]: indexs.pop() while indexs != [] and sums - queue[indexs[0]]>=k: ans = min(ans,idx - indexs[0]) indexs.pop(0) indexs.append(idx) return ans if ans <= len(nums) else-1
classSolution(object): defcombinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ if candidates == []: return [] candidates.sort() defdfs(candidates,target,pos,res,ans): if target == 0: if res notin ans: ans.append(res) return for i in range(pos,len(candidates)): if i > pos and candidates[i] == candidates[i-1]: continue if target >= candidates[i]: dfs(candidates,target-candidates[i],i+1,res + [candidates[i]],ans) else: break ans = [] dfs(candidates,target,0,[],ans) return ans
26. 树的子结构
子结构,可以只是树的一部分,子树要求到叶子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defisSubStructure(self, A, B): """ :type A: TreeNode :type B: TreeNode :rtype: bool """ if A == Noneor B == None: returnFalse defdfs(A,B): if B == None: returnTrue if A == None: returnFalse return A.val == B.val and dfs(A.left,B.left) and dfs(A.right,B.right) return dfs(A,B) or self.isSubStructure(A.left,B) or self.isSubStructure(A.right,B)
classSolution(object): defrotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if head == None: return head n = 0 tmp = head while tmp: if tmp.next == None: tail = tmp tmp = tmp.next n += 1 k %= n if k == 0: return head k = n - k tmp = head tail.next = head for _ in range(k-1): tmp = tmp.next new_head = tmp.next tmp.next = None return new_head
classSolution(object): defgenerateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ if n == 0: return [] matrix = [[0] * n for _ in range(n)] pox,poy = 0,0 lenx,leny = n-1,n-1 value = 1 while pox <= lenx and poy <= leny: for i in range(poy,leny+1): matrix[pox][i] = value value += 1 pox += 1 if pox > lenx: return matrix for i in range(pox,lenx+1): matrix[i][leny] = value value += 1 leny -= 1 if poy > leny: return matrix for i in range(poy,leny+1)[::-1]: matrix[lenx][i] = value value += 1 lenx -= 1 if pox > lenx: return matrix for i in range(pox,lenx+1)[::-1]: matrix[i][poy] = value value += 1 poy += 1 return matrix
21. 调整数组顺序使奇数在偶数前
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): defexchange(self, nums): """ :type nums: List[int] :rtype: List[int] """ left = 0 right = len(nums) - 1 while left < right: while left < right and nums[left] % 2 == 1: left += 1 while left < right and nums[right] % 2 == 0: right -= 1 if left >= right: return nums else: nums[left],nums[right] = nums[right],nums[left] return nums
71. 简化路径
化简linux路径。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defsimplifyPath(self, path): """ :type path: str :rtype: str """ if path == '': return'' res = path.split('/') ans = [] for val in res: if val == '.'or len(val) == 0: continue elif val =='..': if ans != []: ans.pop() else: ans.append(val) return'/' + '/'.join(ans)
classSolution(object): defnextGreaterElement(self, n): """ :type n: int :rtype: int """ if0 <= n < 10: return-1 strs = str(n) nums = [c for c in strs] pos = len(nums) - 2 while pos >= 0and nums[pos] >= nums[pos + 1]: pos -= 1 if pos < 0: return-1 left = pos + 1 right = len(nums) - 1 for i in range(left,right + 1)[::-1]: if nums[pos] < nums[i]: nums[pos],nums[i] = nums[i],nums[pos] break left = pos + 1 right = len(nums) - 1 while left < right: nums[left],nums[right] = nums[right],nums[left] left += 1 right -= 1 res = int(''.join(nums)) return res if res <= 2**31-1else-1
classSolution(object): defmaximumSwap(self, num): """ :type num: int :rtype: int """ str_num = [val for val in str(num)] sort_num = sorted(str_num)[::-1] small = '' big = '' for i in range(len(str_num)): if str_num[i] != sort_num[i]: small = str_num[i] big = sort_num[i] str_num[i] = big break if small != '': for i in range(len(str_num))[::-1]: if str_num[i] == big: str_num[i] = small break return int(''.join(str_num))
classSolution(object): defpermutation(self, s): """ :type s: str :rtype: List[str] """ if s == []: return [] defdfs(s,ans,res,visit): if len(res) == len(s): if res notin ans: ans.append(res) return for i in range(len(s)): if visit[i] == 0: visit[i] = 1 dfs(s,ans,res+s[i],visit) visit[i] = 0 ans = [] visit = [0]*len(s) dfs(s,ans,'',visit) return ans
数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defnextGreaterElements(self, nums): """ :type nums: List[int] :rtype: List[int] """ stack = [] N = len(nums) res = [-1]*N for i in range(2*N): while stack and nums[stack[-1]] < nums[i % N]: res[stack.pop()] = nums[i%N] stack.append(i%N) return res
91.解码方法
将数字转成字母,有几种转法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defnumDecodings(self, s): """ :type s: str :rtype: int """ if s == '': return0 if s[0] == '0': return0 dp = [0] * (len(s) + 1) dp[0] = 1 dp[1] = 1 for i in range(2,len(s) + 1): if s[i-1] !='0': dp[i] += dp[i-1] if s[i-2] != '0'and int(s[i-2:i]) <= 26: dp[i] += dp[i-2] return dp[-1]
136. 只出现过一次的数字
1 2 3 4 5 6 7 8 9 10
classSolution(object): defsingleNumber(self, nums): """ :type nums: List[int] :rtype: int """ res = 0 for val in nums: res ^= val return res
defpaixu(nums,left,right): if left > right: return low = left high = right pivot = nums[low] while left <right: while left < right and nums[right] > pivot: right -= 1 while left < right and nums[left] <= pivot: left -= 1 nums[left],nums[right] = nums[right],nums[left] nums[low] = nums[left] nums[left] = pivot paixu(nums,0,left - 1) paixu(nums,left+1,high)
选择排序
每次选择剩余数组中最小的,放到左边。
不稳定的排序,时间复杂度为$O(n^2)$
1 2 3 4 5 6
defxuanzhepaixu(nums): for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i] > nums[j]: nums[i],nums[j] = nums[j],nums[i] return nums
插入排序
以外循环为核心,对于i -> i-1的元素,对i依次进行比较后交换。
稳定排序,内排序,时间复杂度:$O(n^2)$
1 2 3 4 5 6 7
defcharu(nums): for i in range(1,len(nums)): while i > 0and nums[i] < nums[i-1]: nums[i],nums[i-1] = nums[i-1],nums[i] i -= 1 return nums return charu(nums)
defmerge_sort(nums): if len(nums) == 1: return nums mid = len(nums) // 2 left = merge_sort(nums[:mid]) right = merge_sort(nums[mid:]) return merge(left,right) defmerge(left,right): res = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: res.append(left[i]) i += 1 else: res.append(right[j]) j += 1 res += left[i:] res += right[j:] return res return merge_sort(nums)
defcreate_heap(nums,n,root): left = 2*root + 1 right = 2*root + 2 max_index = root if left <= n and nums[left] > nums[root]: max_index = left if right <= n and nums[right] > nums[max_index]: max_index = right if max_index != root: nums[max_index],nums[root] = nums[root],nums[max_index] create_heap(nums,n,max_index)
defheap_sort(nums): if nums==[]: return nums n = len(nums) - 1 last_index = (n-1)//2 for i in range(last_index+1)[::-1]: create_heap(nums,n,i) heap_sort(nums) for i in range(1,len(nums))[::-1]: nums[0],nums[i] = nums[i],nums[0] create_heap(nums,i-1,0) return nums