![](https://img-blog.csdnimg.cn/20201014180756916.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
leetcode
JasonDecode
这个作者很懒,什么都没留下…
展开
-
98. Validate Binary Search Tree
/ 21 / 31: return True, 3: return True. 2: return True# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightcla原创 2021-09-26 11:56:54 · 83 阅读 · 0 评论 -
32. Longest Valid Parentheses
思想: stack保存下标第一个为-1, 因为需要保证stack里面数字的连续性,才能计数。比如:1 [()]第一次遍历,stack = [-1, 0], -1和0连续,第二次遍历,stack = [-1], i = 1, res = 1-(-1) = 2, 为正确结果。2 [))]第一次遍历,stack = [], 然后stack = [0]第二次遍历,stack = [], 然后stack = [1], 结束循环,因为没有遇到“(”, 所以结果为0.2 [))()()]第一次遍历,s原创 2021-09-12 15:18:21 · 84 阅读 · 0 评论 -
494. Target Sum
这道题使用暴力dfs无法ac, 需要用到memo记忆,避免dfs时,太多的重复。1 memo: 一般用字典记忆。记忆的就是dp的输入状态。如果后续的输入用到之前计算过的,直接用memo。2 比如:Input: nums = [1,1,1], target = 2按照暴力,2 ^ 3 = 8种答案,选取其中target = 2的结果Output: 3-1 + 1 + 1 = 2+1 - 1 + 1 = 2+1 + 1 - 1 = 2这样很费时间,如果用memo:1st: dp(0, 0) -原创 2021-09-12 14:30:30 · 92 阅读 · 0 评论 -
81. Search in Rotated Sorted Array II
重复元素会影响到运行。method 1:bruteclass Solution: def search(self, nums: List[int], target: int) -> bool: for i in nums: if i == target: return True return Falsemethod 2:binaryclass Solution: def search(se原创 2021-09-11 21:22:40 · 89 阅读 · 0 评论 -
74. Search a 2D Matrix
method 1: brute forceclass Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == target:原创 2021-09-11 21:05:52 · 68 阅读 · 0 评论 -
84. Largest Rectangle in Histogram
84. Largest Rectangle in Histogram今天突然发现如果遇到hard题型总是跳过的方法是不会进步的。至少应该能想到用brute force,虽然无法AC,但至少通过了一些测试,然后在想能不能优化。class Solution: def largestRectangleArea(self, heights: List[int]) -> int: res = 0 for i in range(len(heights)):原创 2021-09-11 15:07:34 · 47 阅读 · 0 评论 -
217. Contains Duplicate - 219. Contains Duplicate II
217. Contains Duplicate方法1:set最慢速度class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(nums) != len(set(nums))方法2: set, 更慢速度class Solution: def containsDuplicate(self, nums: List[int]) -> bool:原创 2021-09-11 00:29:00 · 80 阅读 · 0 评论 -
leetcode: 2 pointers
算法分析该类题型是很好理解,应该先刷,双指针一般会遇到两种类型,一类是数组双指针在两端,一类是链表指针在两端。如leetcode 11, 15,16,18等等。使用双指针可以把时间从O(n^2)提高到O(n), 一般能减小一个n次方。觉得也没有必要完全按照标签来做,因为如果能用一种其他的方法解题也可以不考虑双指针,目的是解题,方法用自己最擅长的就可以。没有必要为了某一个解题方法重复做太多的题。关键是知道这样的方法。11. Container With Most Water1 lo: left poin原创 2021-09-10 23:07:05 · 96 阅读 · 0 评论 -
43. Multiply Strings
method: 字符转数字记得在学汇编的时候,数字加减也是输入的字符串,需要转化为数字,再做加减。总之不能直接用int(num) 来得到数字,不然不满足题意。def multiply(self, num1: str, num2: str) -> str: return str(self.str_to_int(num1) * self.str_to_int(num2)) def str_to_int(self, n): result=0 fo原创 2021-09-10 21:05:25 · 55 阅读 · 0 评论 -
73. Set Matrix Zeroes
method: color picture本题主要根据计算机视觉学到的着色原理,要想满足条件,需要对没有完成的0做标记,逆向思路就是把完成的做标记。那么再把标记还原了。这里用到float(‘inf’),是python的系统内置无穷大,满足数字的条件,否则无法通过测试。class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything原创 2021-09-10 01:59:25 · 75 阅读 · 0 评论 -
41. First Missing Positive
method 1:可以通过,但不满足空间O(1)当s 不是集合无法通过。数字 i 一定在1到数组长度加1之间,比如nums = [1, 2, 3], 那么结果为4nums = [1, 2, 2], 结果为 3Runtime: 1346 ms, faster than 9.34% of Python3 online submissions for First Missing Positive.class Solution: def firstMissingPositive(self, nums原创 2021-09-10 01:13:36 · 61 阅读 · 0 评论 -
509. Fibonacci Number - 70. Climbing Stairs
1 最慢速度class Solution: def fib(self, n: int) -> int: ''' dp: store all numbers in an array ''' if n <= 1: return n return self.fib(n-2) + self.fib(n-1)2 DP 快速class Solution: def fib(s原创 2021-09-09 13:33:13 · 78 阅读 · 0 评论 -
37. Sudoku Solver
方法:backtracking这种方法是一种考虑到约束条件的回溯法,条件就是当检查每一个数字时,需要考虑每行,每列和所在的单元已经满足条件,这种问题又叫做满足约束条件问题,backtracking是最好理解的,就是按照每行每列组个元素检验,并填入新的满足条件的元素,一旦到达某一不,不满足时,用backtracking返回上一步,再带入新的元素检查,这种算法一般不用求时间复杂度,因为是NP 问题。更好的方法有前馈和arc consistency 和 domain spliting,但目前不会应用。cla原创 2021-09-08 21:59:18 · 61 阅读 · 0 评论 -
36. Valid Sudoku
1 check each row2 check each cols3 check each boxclass Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: return self.rowsValid(board) and self.colsValid(board) and self.boxesValid(board) box_size = 3 board_size =.原创 2021-09-08 20:14:08 · 48 阅读 · 0 评论 -
44. Wildcard Matching
方法:DP本题难度低于leetcode 10, 二十分钟做完,debug几个边界条件问题。代码运行时间较长1s python,应该有优于dp的算法。class Solution: def isMatch(self, s: str, p: str) -> bool: dp = [[False for j in range(len(p) + 1)] for i in range(len(s) + 1)] dp[0][0] = True for原创 2021-09-08 18:32:44 · 70 阅读 · 0 评论 -
27. Remove Element
class Solution: def removeElement(self, nums: List[int], val: int) -> int: i = len(nums) - 1 while i >= 0: if nums[i] == val: nums.remove(nums[i]) i -= 1 return len(nums)原创 2021-09-07 16:29:15 · 59 阅读 · 0 评论 -
26. Remove Duplicates from Sorted Array
method: 一次遍历,一个指针指向空位填充class Solution: def removeDuplicates(self, nums: List[int]) -> int: index = 1 for i in range(1, len(nums)): if nums[i-1] != nums[i]: nums[index] = nums[i] index += 1原创 2021-09-07 16:19:54 · 50 阅读 · 0 评论 -
leetcode 11-20 总结
11. Container With Most Watermethod: 2 pointers1 i: left pointer, j: right pointer, at both side2 this may have the largest value, then i to right, j to left3 until i >= j, stop loops and return resultpythonclass Solution: def maxArea(self, he原创 2021-09-07 15:28:43 · 95 阅读 · 0 评论 -
145. Binary Tree Postorder Traversal
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclass Solution: def __init__(self): self.res = []原创 2021-09-07 13:33:36 · 59 阅读 · 0 评论 -
144. Binary Tree Preorder Traversal
method: binary tree travesal1 很多人不理解树的递归return的意思,其实有多种写法2 首先不管怎么遍历,肯定要递归,因为树是有结构的,比如二叉树。3 另外,递归时要出现无限的分支,这样形成了无限多的递归子函数,每一个函数必须有终止条件,比如Fibonacci数列的终止条件是数字,这里时return4 这里的每一个return self.res是其中某一个的终止条件,最终结果时函数全部递归完的return self.res# Definition for a bina原创 2021-09-07 13:27:28 · 61 阅读 · 0 评论 -
100. Same Tree
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclass Solution: def isSameTree(self, p: Optional[TreeNode],原创 2021-09-07 12:57:40 · 60 阅读 · 0 评论 -
94. Binary Tree Inorder Traversal
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclass Solution: def __init__(self): self.res = []原创 2021-09-07 12:43:08 · 82 阅读 · 0 评论 -
20. Valid Parentheses
method 1: replace, 没学数据结构前class Solution: def isValid(self, s: str) -> bool: while "()" in s or "{}" in s or '[]' in s: s = s.replace("()", "").replace('{}', "").replace('[]', "") return s == ''method 2: stack 学了数据结构c原创 2021-09-07 01:26:50 · 86 阅读 · 0 评论 -
14. Longest Common Prefix
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: prefix = [] # zip to [('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g')] for item in zip(*strs): if len(set(item)) != 1:原创 2021-09-07 00:56:05 · 73 阅读 · 0 评论 -
12. Integer to Roman
class Solution: def intToRoman(self, num: int) -> str: value = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] roman = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] res = "" for idx, val in enumer原创 2021-09-07 00:43:14 · 68 阅读 · 0 评论 -
13. Roman to Integer
method1: 之前的太繁琐这样写不符合程序设计,虽然可读,但不简洁。class Solution: def romanToInt(self, s: str) -> int: num = 0 i = 0 while i < len(s): if i < len(s) and s[i] == 'M': num += 1000 i += 1原创 2021-09-06 23:58:01 · 51 阅读 · 0 评论 -
25. Reverse Nodes in k-Group
method: 24# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution: def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[L原创 2021-09-06 00:40:06 · 51 阅读 · 0 评论 -
24. Swap Nodes in Pairs
method: linked list# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[List原创 2021-09-06 00:37:56 · 76 阅读 · 0 评论 -
23. Merge k Sorted Lists
method: pq# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: # pq原创 2021-09-05 23:48:51 · 65 阅读 · 0 评论 -
leetcode 21-30 总结
6. ZigZag Conversion方法:利用bucket sort 的原理想了几天没想出来,想得到一个特定模式,但没找到,其实用bucket的原理很容易解决。Z字形的字符串按照顺序放在bucket里,然后把bucket连接起来,考虑边界条件如何放置,需要用到一个flip变量,控制如何放。Input: s = “PAYPALISHIRING”, numRows = 4Output: “PINALSIGYAHRPI”Explanation:P I N原创 2021-09-05 12:25:57 · 278 阅读 · 0 评论 -
18. 4Sum
method: leetcode 15, 16 : 2 pointersclass Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: num_set = set() nums.sort() for i in range(len(nums) - 1): for j in range(i + 1, len(nums)):原创 2021-09-05 01:55:38 · 52 阅读 · 0 评论 -
16. 3Sum Closest
method: 2 pointersclass Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = set() nums.sort() for i in range(len(nums)): low, high = i + 1, len(nums) - 1 while low < high:原创 2021-09-05 01:41:49 · 67 阅读 · 0 评论 -
8. String to Integer (atoi)
method: no按照题目要求top-down approachclass Solution: def myAtoi(self, s: str) -> int: # 1 strip leading and ending space s = s.strip() signs = ['-', '+'] res = '' # 2 check for sign and numbers and stop conditi原创 2021-09-05 01:30:47 · 50 阅读 · 0 评论 -
10. Regular Expression Matching
method: dp# use dp dp = [[False for j in range(len(p) + 1)] for i in range(len(s) + 1)] dp[0][0] = True # for a*b* cases for i in range(1, len(p) + 1): if p[i-1] == "*" and dp[0][i - 2]: dp[0][i]原创 2021-09-05 01:06:48 · 153 阅读 · 0 评论 -
9. Palindrome Number
方法:第5题的子问题,又和第7题的解题方法一样,做题顺序应该是9 -> 5, 71 用数字逆序处理,第7题方法class Solution: def isPalindrome(self, x: int) -> bool: check_num = x new_num = 0 if x < 0: return False while x >0: remainder原创 2021-09-04 21:49:35 · 71 阅读 · 0 评论 -
7. Reverse Integer
方法:数学也没什么好的方法,这种题应该经常做,固定的方法逆序一个数字,难点是需要考虑边界条件与负数的逆序处理。class Solution: def reverse(self, x: int) -> int: def reverse_pos_int(num): reversed_num = 0 while num: remainder = num % 10 rev原创 2021-09-04 21:38:00 · 103 阅读 · 0 评论 -
6. ZigZag Conversion
方法:利用bucket sort想了几天没想出来,想得到一个特定模式,但没找到,其实用bucket的原理很容易解决。Z字形的字符串按照顺序放在bucket里,然后把bucket连接起来,考虑边界条件如何放置,需要用到一个flip变量,控制如何放。 ''' time: O(n+k < n + n) = O(n), n is number of char in str and k is number of rows space: O(n) '''原创 2021-09-04 21:31:30 · 75 阅读 · 0 评论 -
leetcode 1-10 总结
1. Two Sum方法1:暴力群举没学算法前,觉得只要暴力能解决的问题就不叫问题,于是幼稚的认为这样就可以:class Solution: def twoSum(self, nums, target): for i in range(len(nums) - 1): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target:原创 2021-09-02 22:15:46 · 273 阅读 · 0 评论 -
19. Remove Nth Node From End of List
method: 2 pass1 first pass count number of nodes2 second pass remove nodePython:class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: p = q = dummy = ListNode(0) dummy.next = head原创 2021-08-30 18:31:21 · 73 阅读 · 0 评论 -
15. 3Sum - 16. 3Sum Closest - 18. 4Sum
method: 2 pointers1 prepare a set2 sort the array3 for each i loop, use 2 pointers to reduce time in sorted array4 use set to avoid repeatingPython:class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: output = set()原创 2021-08-30 18:15:02 · 114 阅读 · 0 评论