![](https://img-blog.csdnimg.cn/20201014180756919.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
LeetCode每日一题
LeetCode美区每日一题解法分享
SincX
向AI编译器方向努力
展开
-
[LeetCode Python3] 396. Rotate Function + 暴力 + 错位相减
396. Rotate Function暴力 时间复杂度O(n*n)按照计算规则,一步一步来class Solution: def maxRotateFunction(self, nums: List[int]) -> int: size, res = len(nums), -float('inf') for i in range(size): tmp = 0 for j in range(size):原创 2021-04-27 20:14:08 · 118 阅读 · 0 评论 -
[LeetCode Python3]395. Longest Substring with At Least K Repeating Characters +递归
395. Longest Substring with At Least K Repeating Charactersclass Solution: def longestSubstring(self, s: str, k: int) -> int: if len(s) < k: return 0 for c in set(s): # 若某个字符c的个数大于0且小于k,那么包含它的子串必然不符合要求,原创 2021-04-26 19:44:51 · 186 阅读 · 0 评论 -
[LeetCode Python3] 394. Decode String + 递归
394. Decode Stringclass Solution: def decodeString(self, s: str) -> str: table = "0123456789" size = len(s) index = 0 res = "" while index < size: if s[index] in table: # 若遇到数字即进入解码原创 2021-04-22 17:42:39 · 147 阅读 · 0 评论 -
[LeetCode Python3] 393. UTF-8 Validation +位处理
393. UTF-8 Validationsymple & 128 == 0 表示symple必为 0xxx xxxx(symple & 128 == 128) and (symple & 64 == 0) 表示symple必为 10xx xxxx(symple & 192 == 192) and (symple & 32 == 0) 表示symple必为 110x xxxx(symple & 224 == 224) and (symple &原创 2021-04-21 21:15:42 · 91 阅读 · 0 评论 -
[LeetCode Pythons] 388. Longest Absolute File Path+O(n)
#388. Longest Absolute File Path算法搬运工解题思路使用一个数组prefixSum,保存遍历过程中,已知层级的前缀字符串数。如前缀为aaa/bb/cc/则prefixSum = [0, 4, 7, 10], 即aaa/的长度,aaa/bb/的长度,aaa/bb/cc/的长度。在遍历每行数据时:保存当前行的层级level,也就是\t的数量。如果当前行为文件: 我们只要将当前文件名的长度,加上之前层级的字符串长度就行。如果当前行为文件夹: 如果层级比数组长度大,原创 2021-04-12 20:09:30 · 82 阅读 · 0 评论 -
[LeetCode Python3] 384. Shuffle an Array +洗牌算法
384. Shuffle an Array暴力重排class Solution: def __init__(self, nums: List[int]): self.nums = nums[:] self.tmp = nums[:] def reset(self) -> List[int]: """ Resets the array to its original configuration and return原创 2021-04-05 11:03:56 · 110 阅读 · 0 评论 -
[LeetCode Python3] 382. Linked List Random Node + 水塘抽样 +大数据流,等概率抽样
382. Linked List Random Nodeclass Solution: def __init__(self, head: ListNode): self.head = head def getRandom(self) -> int: count = 0 reserve = self.head.val cur = self.head while cur: count原创 2021-04-05 09:56:41 · 115 阅读 · 0 评论 -
[LeetCode Python3]334. Increasing Triplet Subsequence + 暴力搜索 + 双指针
334. Increasing Triplet Subsequence暴力搜索class Solution: def increasingTriplet(self, nums: List[int]) -> bool: size = len(nums) if size < 3: return False for i in range(size-2): for j in range(i+1,原创 2021-02-07 15:26:20 · 98 阅读 · 0 评论 -
[LeetCode Python3] 318. Maximum Product of Word Lengths + 位掩码
318. Maximum Product of Word Lengthsfrom collections import defaultdictclass Solution: def maxProduct(self, words: List[str]) -> int: hashmap = defaultdict(int) bit_number = lambda ch: ord(ch) - ord('a') for word in words原创 2021-02-07 14:40:50 · 110 阅读 · 0 评论 -
332. Reconstruct Itinerary +欧拉通路
332. Reconstruct Itineraryclass Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: def dfs(curr: str): while vec[curr]: tmp = heapq.heappop(vec[curr]) dfs(tmp) s原创 2021-02-03 16:48:07 · 132 阅读 · 0 评论 -
[LeetCode Python3] 260. Single Number III +集合
260. Single Number III集合的删除、添加、查找的时间复杂度均为O(1)Time:O(n); Space: O(3)class Solution: def singleNumber(self, nums: List[int]) -> List[int]: res = set() for num in nums: if num in res: res.remove(num)原创 2021-01-20 19:34:41 · 78 阅读 · 0 评论 -
[LeetCode Python3]274/275. H-Index I/II
275. H-Index IIO(n)class Solution: def hIndex(self, citations: List[int]) -> int: res = 0 for index in range(len(citations)): if citations[len(citations)-1-index] >= index + 1: res = index + 1原创 2021-01-20 19:24:07 · 108 阅读 · 0 评论 -
[LeetCode Python3] 240. Search a 2D Matrix II +二分查找
240. Search a 2D Matrix II二维版二分查找class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: m, n = len(matrix), len(matrix[0]) def helper(rlo, rhi, clo, chi): if rlo >= rhi or clo >= ch原创 2021-01-16 16:40:39 · 104 阅读 · 0 评论 -
[LeetCode Python3]222. Count Complete Tree Nodes +完全二叉树/满二叉树
222. Count Complete Tree Nodes满二叉树、完全二叉树、平衡二叉树、最优二叉树class Solution: def countNodes(self, root: TreeNode) -> int: def getheight(root): # 得到完全二叉树的高度 height = 0 while root: height += 1原创 2021-01-12 19:47:06 · 70 阅读 · 0 评论 -
[LeetCode Python3] 217/219/220. Contains Duplicate I/II/III
217. Contains Duplicatesolution1:统计每个元素出现的个数,当个数超过1时说明重复class Solution: def containsDuplicate(self, nums: List[int]) -> bool: dic = collections.defaultdict(int) for num in nums: dic[num] += 1 for key, value in原创 2021-01-11 21:33:09 · 108 阅读 · 0 评论 -
[LeetCode Python3] 209. Minimum Size Subarray Sum + O(n) + 滑动窗口
209. Minimum Size Subarray Sum滑动窗口class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: left, right, size = 0, 0, len(nums) # left, right分别记录滑动窗口的左右边界,左闭右开 subsum, minlen = 0, size+1 # minlen的初始化用size+1代替正无穷原创 2021-01-07 11:37:21 · 91 阅读 · 1 评论 -
[LeetCode Python3] 207. Course Schedule+ DFS
207. Course Schedule该题本质是判断图中是否存在环,这里采用深度优先搜索求解Solution:class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: def dfs(i): visited[i] = 1 if i in graph: for t原创 2021-01-05 19:54:25 · 91 阅读 · 1 评论 -
[LeetCode Python3] 199. Binary Tree Right Side View +层次遍历
199. Binary Tree Right Side View该题的本质还是层次遍历,只不过仅把每层的最右边元素记录下来solution:class Solution: def rightSideView(self, root: TreeNode) -> List[int]: if not root: return [] que = [root] que1 = [] res = []原创 2021-01-04 19:33:03 · 78 阅读 · 0 评论 -
[LeetCode Python3] 187. Repeated DNA Sequences
187. Repeated DNA Sequencesclass Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: dictionary = dict() for i in [s[x : x + 10] for x in range(len(s) - 9)]: dictionary[i] = dictionary.get(i, 0) + 1原创 2021-01-03 19:57:04 · 78 阅读 · 0 评论 -
[LeetCode Python3] 173. Binary Search Tree Iterator +由中序遍历程序改造 + Time:O(1),Space:O(h)
173. Binary Search Tree Iterator由题意迭代器要按升序逐一迭代访问,因为二叉搜索树的中序遍历序列就是严格按升序排列的由此先给出二叉树的中序遍历程序中序遍历程序:class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [] stack = [原创 2021-01-01 16:43:22 · 98 阅读 · 0 评论 -
[LeetCode Python3] 150. Evaluate Reverse Polish Notation
150. Evaluate Reverse Polish Notation参考资料:如何用栈求表达式的值Solution:class Solution: def evalRPN(self, tokens: List[str]) -> int: operators = ["+", "-", "*", "/"] stack = [] for token in tokens: if token in operators:原创 2020-12-29 19:28:50 · 94 阅读 · 0 评论 -
[LeetCode Python3] 144. Binary Tree Preorder Traversal +递归+迭代
144. Binary Tree Preorder Traversal递归class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [root.val] if root.left: res += self.preorderTraversal(root原创 2020-12-27 15:57:18 · 75 阅读 · 1 评论 -
[LeetCode Python3]139. Word Break +暴力递归 + 带备忘录的递归
暴力递归class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: def helper(tmps): if not tmps: # tmps为空字符串是返回真 return True for i in range(1, len(tmps)+1): if tmps[:i]原创 2020-12-26 20:51:43 · 130 阅读 · 0 评论 -
[LeetCode Python3] 134. Gas Station+暴力遍历+简单剪枝
134. Gas Stationclass Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: size = len(gas) for index in range(size): #遍历所有站,只要当前油站的油量大于该站到下一站要耗的油量时才有可能作为起点 if gas[index] >= cost[index]:原创 2020-12-25 21:17:31 · 118 阅读 · 0 评论 -
[LeetCode Python3] 131. Palindrome Partitioning +递归+划分子问题
131. Palindrome PartitioningSolution:class Solution: def validpalindrome(self, s): if len(s) == 1: return True lo, hi = 0, len(s)-1 while lo < hi: if s[lo] != s[hi]: return False原创 2020-12-23 21:16:18 · 74 阅读 · 0 评论 -
[LeetCode Python3] 129. Sum Root to Leaf Numbers +递归
129. Sum Root to Leaf Numbers解题思路:二叉树首先往递归上想,标准模板:def fun(root,..): if not root: return .. if root.left: fun(root.left,..) if root.right: fun(root.right,..) return ..本题解法:class Solution: def sumNumbers(self, root: TreeNode) -> int:原创 2020-12-22 20:22:53 · 98 阅读 · 0 评论 -
[LeetCode Python3] 127. Word Ladder + BFS +双向BFS
127. Word Ladder + BFS +双向BFS1、BFSfrom collections import defaultdictclass Solution(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str]原创 2020-10-26 16:17:55 · 137 阅读 · 0 评论 -
[LeetCode Python3] 97. Interleaving String + 暴力递归 + 带备忘录的递归 + 动态规划
97. Interleaving String暴力递归# V1 暴力class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: size1, size2, size3 = len(s1), len(s2), len(s3) if size1 + size2 != size3: # 当s1和s2的长度加起来不等于s3的长度,肯定无法交错组成原创 2020-10-22 10:46:33 · 133 阅读 · 0 评论 -
[LeetCode Python3] 103. Binary Tree Zigzag Level Order Traversal + 两种解法
103. Binary Tree Zigzag Level Order TraversalS1:# V1 class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return None res, restmp = [], [] stack0, stack1 = [root], []原创 2020-10-20 18:58:34 · 160 阅读 · 0 评论 -
[LeetCode Python3] 94. Binary Tree Inorder Traversal +二叉树前序遍历+递归解法+迭代解法
94. Binary Tree Inorder TraversalS1: 递归class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [] if root.left: res += self.inorderTraversal(root.left)原创 2020-10-19 21:54:57 · 161 阅读 · 0 评论 -
[LeetCode Python3] 93. Restore IP Addresses + 回溯 + 注释详解
93. Restore IP Addresses# Runtime: 20 ms, faster than 99.80%; Memory Usage: 14.2 MB, less than 100.00%class Solution: def restoreIpAddresses(self, s: str) -> List[str]: res = [] def trackback(track, index, size): if ind原创 2020-10-19 21:23:08 · 123 阅读 · 0 评论 -
[LeetCode Python3] 89. Gray Code +格雷码与二进制码的转换
89. Gray Code# Runtime: 24 ms, faster than 97.33%; Memory Usage: 14.3 MB, less than 6.42%class Solution: def grayCode(self, n: int) -> List[int]: res = [] for i in range(2**n): tmp = i >> 1 ^ i # 右移一位然后与本身异或原创 2020-10-19 10:47:51 · 143 阅读 · 0 评论 -
[LeetCode Python3] 86. Partition List +哨兵节点
86. Partition List# Runtime: 36 ms, faster than 62.35%; Memory Usage: 14 MB, less than 100.00%class Solution: def partition(self, head: ListNode, x: int) -> ListNode: ahead = ListNode() # 建立原链表的哨兵节点,用于删除比x小的节点 bhead = ListNode()原创 2020-10-19 10:29:04 · 160 阅读 · 0 评论 -
[LeetCode Python3] 84. Largest Rectangle in Histogram+O(n^2)+O(n)
84. Largest Rectangle in HistogramS1: Time O(n^2)class Solution: def largestRectangleArea(self, heights: List[int]) -> int: if not heights: return 0 size = len(heights) dp = [[0]*size for _ in range(size)]原创 2020-10-18 20:14:38 · 175 阅读 · 0 评论 -
[LeetCode Python3] 82. Remove Duplicates from Sorted List II+哨兵节点
82. Remove Duplicates from Sorted List II# Runtime: 40 ms, faster than 78.38%; Memory Usage: 14.2 MB, less than 99.93%class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return head ahea原创 2020-10-18 17:45:56 · 69 阅读 · 0 评论 -
[LeetCode Python3] 80. Remove Duplicates from Sorted Array II+双指针
80. Remove Duplicates from Sorted Array II# Runtime: 52 ms, faster than 83.68%; Memory Usage: 14.1 MB, less than 99.96%class Solution: def removeDuplicates(self, nums: List[int]) -> int: if not nums: return 0 left, righ原创 2020-10-18 14:44:05 · 56 阅读 · 0 评论 -
[LeetCode Python3]77. Combinations回溯
77. Combinationsclass Solution: def __init__(self): self.res = [] def trackback(self, track, index, n, k): if len(track) == k: self.res.append(track[:]) return for i in range(index+1, n+1): #选择列表原创 2020-10-18 13:33:02 · 57 阅读 · 0 评论 -
[LeetCode Python] 71. Simplify Path
71. Simplify Pathclass Solution: def simplifyPath(self, path: str) -> str: path = path.split("/") res = [] for i in range(len(path)): if path[i] == "." or path[i] == "": continue elif原创 2020-10-18 12:35:51 · 68 阅读 · 0 评论 -
[LeetCode Python3] 63. Unique Paths II
63. Unique Paths IIclass Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: if not obstacleGrid or not obstacleGrid[0]: return 0 if obstacleGrid[0][0] == 1: return 0 m原创 2020-10-16 19:55:43 · 79 阅读 · 0 评论 -
[LeetCode Python3] 62. Unique Paths
62. Unique Pathsclass Solution: def uniquePaths(self, m: int, n: int) -> int: res = [[1]*n for _ in range(m)] for i in range(1, m): for j in range(1, n): res[i][j] = res[i-1][j] + res[i][j-1] retu原创 2020-10-16 19:54:43 · 93 阅读 · 0 评论