Leet Code 刷题笔记 - - 不求最快最省,但求最短最优雅

前言

  • 代码精炼是 Python 的核心,同时能够反应对于语言的熟练程度,本项目目的在于汇总 leet code 最短最优雅的解法,拒绝长篇大论,缩短学习周期,掌握各种技巧,助您在面试中写出令人眼前一亮的解答,给考官留个好印象。
  • 为什么我们追求最短?1.短代码更pythonic,而且通常能够避免一些冗余过程。2.除了刷题掌握算法思路之外,我们更追求深入理解和掌握python,学会套用技巧,举一反三。3.真正面试的时候不一定要这么短,可以适当展开几行(O_o 除非你就是想秀其他人一脸 ?),保证思路更清晰,相信就算展开几行也会比其他题解短很多吧。4.刷题很累,找点乐子,送给自己一些成就感吧。5.所有已收录代码都是优中选优,题库解析部分除了短代码外,也有常规解法作为补充。6.若基础知识不够扎实,可以先看专题探索部分,然后再转题库解析学习 Python 中隐藏的先进技巧。
  • 项目持续更新中,优先使用 python3,不支持的题目使用 python2 代替,如果您有更短更优雅的解法希望分享的话欢迎联系更新~ [直接发issue 或 fork,记得留下署名和联系方式 ?] 鉴于追求的主题,此项目收录 1.在代码量(不是行数)上明显优于现有解的最短代码 2.思路更高效的一般解法(作为补充放在首选解之后) [题目自带的代码不计入代码量]
  • 如果您对当前解析有任何疑问,咱们 issue 见~
  • 由于CSDN博客更新需要人工审核比较慢,所以迁移到github上,优先更新github内容。
  • 为了快速找到题目可以按 [Ctrl键 + F键] 输入题目序号或名字定位。
  • 欢迎加入QQ交流群:902025048 ∷二维码 群内提供更多相关资料~

重要说明

  • 由于项目需要频繁更新,CSDN每次都需要人工审核,更新的时候打不开,不太方便,项目迁移至 Github,优先更新github。
  • 由于写法不同,博客中的超链接可能失效。

? 里程碑

  • ? 腾讯精选练习(50题: 25简单 21中等 4困难) 代码行数 总计:140行 平均:2.8行 ? 题目详情 ? 2019/05/05

推荐

  • 与本项目有关联的,? 是一个 C++最清晰题解汇总 ?。Python篇注重熟悉语言特性,充分利用高级语言提供的已内置的功能避免冗余编码,最低成本地解决问题。C++篇注重通用思想,分专题逐个击破,深入探究算法流程。俩者同时服用效果更佳,只想学一门也不必担心,俩个项目相辅相成,Python篇会在题解之后添加常规解法作为补充,并根据官方推荐的路线总结一套专题探索,C++篇会利用python题解的思想优化代码,保证代码简洁,可读性高。
  • ? 推荐刷题路线:专题探索 → 腾讯精选50题 → 题库解析

题库解析

此专栏追求代码的精简技巧性,默认已看过题目,? 没看过的话点标题可以跳转链接,咱们一起体验炫酷的 Python

1. Two Sum 4行

class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:d = {}for i, n in enumerate(nums): if n in d: return [d[n], i]d[target-n] = i

2. Add Two Numbers 5行

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def addTwoNumbers(self, l1: ListNode, l2: ListNode, carry=0) -> ListNode:if not (l1 or l2): return ListNode(1) if carry else Nonel1, l2 = l1 or ListNode(0), l2 or ListNode(0)val = l1.val + l2.val + carryl1.val, l1.next = val % 10, self.addTwoNumbers(l1.next, l2.next, val > 9)return l1

3. Longest Substring Without Repeating Characters 3行

class Solution:def lengthOfLongestSubstring(self, s: str) -> int:b, m, d = 0, 0, {}for i, l in enumerate(s): b, m, d[l] = max(b, d.get(l, -1) + 1), max(m, i - b), ireturn max(m, len(s) - b)

4. Median of Two Sorted Arrays 5行

class Solution:def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:a, b, m = *sorted((nums1, nums2), key=len), (len(nums1) + len(nums2) - 1) // 2self.__class__.__getitem__ = lambda self, i: m-i-1 < 0 or a[i] >= b[m-i-1]i = bisect.bisect_left(self, True, 0, len(a))r = sorted(a[i:i+2] + b[m-i:m-i+2])return (r[0] + r[1 - (len(a) + len(b)) % 2]) / 2

5. Longest Palindromic Substring 5行

class Solution:def longestPalindrome(self, s: str) -> str:r = ''for i, j in [(i, j) for i in range(len(s)) for j in (0, 1)]:while i > -1 and i + j < len(s) and s[i] == s[i + j]: i, j = i - 1, j + 2r = max(r, s[i + 1:i + j], key=len)return '' if not s else r

7. Reverse Integer 2行

class Solution:def reverse(self, x):r = x // max(1, abs(x)) * int(str(abs(x))[::-1])return r if r.bit_length() < 32 or r == -2**31 else 0

8. String to Integer (atoi) 1行

class Solution:def myAtoi(self, s: str) -> int:return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)

9. Palindrome Number 1行

class Solution:def isPalindrome(self, x: int) -> bool:return str(x) == str(x)[::-1]

不使用字符串的进阶解法:

class Solution:def isPalindrome(self, x: int) -> bool:r = list(map(lambda i: int(10**-i * x % 10), range(int(math.log10(x)), -1, -1))) if x > 0 else [0, x]return r == r[::-1]

11. Container With Most Water 3行

class Solution:def maxArea(self, height: List[int]) -> int:res, l, r = 0, 0, len(height) - 1while l < r: res, l, r = (max(res,  height[l] * (r - l)), l + 1, r) if height[l] < height[r] else (max(res,  height[r] * (r - l)), l, r - 1)return res

13. Roman to Integer 2行

class Solution:def romanToInt(self, s: str) -> int:d = {'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000}return sum([d.get(s[max(i-1, 0):i+1], d[n]) for i, n in enumerate(s)])

14. Longest Common Prefix 2行

class Solution:def longestCommonPrefix(self, strs: List[str]) -> str:r = [len(set(c)) == 1 for c in zip(*strs)] + [0]return strs[0][:r.index(0)] if strs else ''

15. 3Sum 5行

class Solution:def threeSum(self, nums: List[int]) -> List[List[int]]:nums, r = sorted(nums), set()for i in [i for i in range(len(nums)-2) if i < 1 or nums[i] > nums[i-1]]:d = {-nums[i]-n: j for j, n in enumerate(nums[i + 1:])}r.update([(nums[i], n, -nums[i]-n) for j, n in enumerate(nums[i+1:]) if n in d and d[n] > j])return list(map(list, r))

16. 3Sum Closest 7行

class Solution:def threeSumClosest(self, nums: List[int], target: int) -> int:nums, r, end = sorted(nums), float('inf'), len(nums) - 1for c in range(len(nums) - 2):i, j = max(c + 1, bisect.bisect_left(nums, target - nums[end] - nums[c], c + 1, end) - 1), endwhile r != target and i < j:s = nums[c] + nums[i] + nums[j]r, i, j = min(r, s, key=lambda x: abs(x - target)), i + (s < target), j - (s > target)return r

20. Valid Parentheses 2行

class Solution:def isValid(self, s: str) -> bool:while any(('()' in s, '[]' in s, '{}' in s)): s = s.replace('()', '').replace('[]', '').replace('{}', '')return not s
  • 不断删除有效括号直到不能删除,思路简单效率低。另外,stack的方法也很简单,而且快多了。

    class Solution:def isValid(self, s: str) -> bool:stack, d = [], {'{': '}', '[': ']', '(': ')'}for p in s:if p in '{[(':stack += [p];elif not (stack and d[stack.pop()] == p):return Falsereturn not stack
    

21. Merge Two Sorted Lists 4行

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:if l1 and l2:if l1.val > l2.val: l1, l2 = l2, l1l1.next = self.mergeTwoLists(l1.next, l2)return l1 or l2

23. Merge k Sorted Lists 4行

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def mergeKLists(self, lists: List[ListNode]) -> ListNode:r, n, p = [], lists and lists.pop(), Nonewhile lists or n: r[len(r):], n = ([n], n.next or lists and lists.pop()) if n else ([], lists.pop())for n in sorted(r, key=lambda x: x.val, reverse=True): n.next, p = p, nreturn n if r else []
  • 本题思路:

    1. 把题目给的所有链表中的所有节点放进一个列表 r。
    2. 对这个列表 r 中的所有节点进行从大到小的排序。O(NlogN)
    3. 把每个节点的指针指向前一个节点。(第一个节点,也就是最大的那个,指向None。)
    4. 返回最后一个节点,也就是整个新链表的开头。
  • 如何把所有节点放进 r(result link)?

    我们首先初始化 r 为空列表,初始化 n(node) 为题目所给的第一个链表的开头节点,并删除lists中的这个节点,接着进入while循环,如果 n 不为空,那么 r += [n],这里使用了切片的技巧(r[len®:]=[n]相当于r=r+[n]),n=n.next,如果n是第一个链表的最后一个节点的话n.next就是None,下一次while的时候如果lists不为空就说明还有别的链表,此时n为None,我们让 r 不变,n=lists.pop(),也就是从lists中再取下一个节点赋值给n,重复以上步骤直到 lists 为空,我们就把所有节点放进 r 了。

  • 怎么对 r 排序?

    用了sorted函数,其中key定义了排序时用来比较的是每个元素的val属性,同时设置reverse为True代表降序排序。

  • 如何修改每个节点的指针?

    我们初始化 p(previous node) 为None。遍历降序排好的列表 r,r中的第一个元素就是值最大的元素,也就是我们应该返回的链表的结尾,我们设置它指向None,然后让p=这个节点,继续for循环。之后每经过一个节点 n 就把这个节点的next属性设置为上一个节点 p,遍历完成之后的 n,也就是我们遍历经过的最后一个元素,拥有最小的值,自然就是整个新链表的起始节点,我们将其作为输出值,函数返回。

26. Remove Duplicates from Sorted Array 3行

class Solution:def removeDuplicates(self, nums: List[int]) -> int:for i in range(len(nums)-1, 0, -1):if nums[i] == nums[i-1]: nums.pop(i)return len(nums)

28. Implement strStr() 1行

class Solution:def strStr(self, haystack: str, needle: str) -> int:return haystack.find(needle)
  • 不用内置函数也可以

    class Solution:def strStr(self, haystack: 'str', needle: 'str') -> 'int':for i in range(0, len(haystack) - len(needle) + 1):if haystack[i:i+len(needle)] == needle:return ireturn -1
    

33. Search in Rotated Sorted Array 3行

class Solution:def search(self, nums, target):self.__class__.__getitem__ = lambda self, m: not(target < nums[0] <= nums[m] or nums[0] <= nums[m] < target or nums[m] < target <= nums[-1])i = bisect.bisect_left(self, True, 0, len(nums))return i if target in nums[i:i+1] else -1

38. Count and Say 1行

class Solution:def countAndSay(self, n: int) -> str:return '1' * (n is 1) or re.sub(r'(.)\1*', lambda m: str(len(m.group())) + m.group(1), self.countAndSay(n - 1))

43. Multiply Strings 5行

class Solution:def multiply(self, num1: str, num2: str) -> str:d = {}for i, n1 in enumerate(num1[::-1]):for j, n2 in enumerate(num2[::-1]): d[i + j] = d.get(i + j, 0) + int(n1) * int(n2)for k in [*d]: d[k + 1], d[k] = d.get(k + 1, 0) + int(d[k] * 0.1), d[k] % 10return re.sub('^0*', '', ''.join(map(str, d.values()))[::-1]) or '0'

46. Permutations 1行

class Solution:def permute(self, nums: List[int]) -> List[List[int]]:return [[n] + sub for i, n in enumerate(nums) for sub in self.permute(nums[:i] + nums[i+1:])] or [nums]
  • 每次固定第一个数字递归地排列数组剩余部分

  • python 有内置函数可以直接实现

    class Solution:def permute(self, nums: List[int]) -> List[List[int]]:from itertools import permutationsreturn list(permutations(nums))
    

53. Maximum Subarray 2行

class Solution:def maxSubArray(self, nums):from functools import reducereturn reduce(lambda r, x: (max(r[0], r[1]+x), max(r[1]+x,x)), nums, (max(nums), 0))[0]
  • reduce 函数详解

  • r[0]代表以当前位置为结尾的局部最优解

  • r[1]代表全局最优解

  • 直接DP的解法更好理解一些

    class Solution:def maxSubArray(self, nums: List[int]) -> int:for i in range(1, len(nums)):nums[i] = max(nums[i], nums[i] + nums[i-1])return max(nums)
    

54. Spiral Matrix 1行

class Solution:def spiralOrder(self, matrix: List[List[int]]) -> List[int]:return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])

58. Length of Last Word 1行

class Solution:def lengthOfLastWord(self, s: str) -> int:return len(s.strip(' ').split(' ')[-1])

59. Spiral Matrix II 3行

class Solution:def generateMatrix(self, n: int) -> List[List[int]]:r, n = [[n**2]], n**2while n > 1: n, r = n - len(r), [[*range(n - len(r), n)]] + [*zip(*r[::-1])]return r
||  =>  |9|  =>  |8|      |6 7|      |4 5|      |1 2 3||9|  =>  |9 8|  =>  |9 6|  =>  |8 9 4||8 7|      |7 6 5|

61. Rotate List 4行

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def rotateRight(self, head: ListNode, k: int) -> ListNode:l = []while head: l[len(l):], head = [head], head.nextif l: l[-1].next, l[-1 - k % len(l)].next = l[0], Nonereturn l[- k % len(l)] if l else None

62. Unique Paths 1行

class Solution:def uniquePaths(self, m: int, n: int) -> int:return int(math.factorial(m+n-2)/math.factorial(m-1)/math.factorial(n-1))

66. Plus One 1行

class Solution:def plusOne(self, digits: List[int]) -> List[int]:return list(map(int, str(int(''.join(map(str, digits))) + 1)))

69. Sqrt(x) 1行

class Solution:def mySqrt(self, x: int) -> int:return int(x ** 0.5)

出题者应该是希望看到下面的答案:

class Solution:def mySqrt(self, x: int) -> int:r = xwhile r*r > x:r = (r + x/r) // 2return int(r)

70. Climbing Stairs 2行

class Solution:def climbStairs(self, n: int) -> int:from functools import reducereturn reduce(lambda r, _: (r[1], sum(r)), range(n), (1, 1))[0]

78. Subsets 2行

class Solution:def subsets(self, nums: List[int]) -> List[List[int]]:from itertools import combinationsreturn sum([list(combinations(nums, i)) for i in range(len(nums) + 1)], [])

88. Merge Sorted Array 1行

class Solution:def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:"""Do not return anything, modify nums1 in-place instead."""while n > 0: nums1[m+n-1], m, n = (nums1[m-1], m-1, n) if m and nums1[m-1] > nums2[n-1] else (nums2[n-1], m, n-1)
  • 这种题倒着算更容易

  • 上面那行代码其实就相当于:

    class Solution:def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:"""Do not return anything, modify nums1 in-place instead."""while n > 0:if m and nums1[m-1] > nums2[n-1]:nums1[m+n-1], m, n = nums1[m-1], m-1, nelse:nums1[m+n-1], m, n = nums2[n - 1], m, n-1
    

89. Gray Code 1行

class Solution:def grayCode(self, n: int) -> List[int]:return (lambda r: r + [x | 1<<n-1 for x in r[::-1]])(self.grayCode(n-1)) if n else [0]
  • 前4个结果:

    [0]
    [0 1]
    [00 01 11 10]
    [000 001 011 010 110 111 101 100]
    
  • 递归方程:这一步结果 = 上一步结果 + 上一步结果的镜像并在每个二进制数字前面加一位1
  • << 左移符号,即在二进制表示后加一位 0 ,例子:3<<1 等于 6(011 → 110),相当于 3 * 2的1次方
  • x | 1<<n-1 就是在十进制数字 x 的二进制前面加一位1之后的十进制结果,比如 x = 1,有 1 | 10 等于 110
  • 循环可以避免一些不必要的操作,会比递归快一些:
    class Solution:def grayCode(self, n: int) -> List[int]:r = [0]for i in range(n):r.extend([x | 1<<i for x in r[::-1]])return r
    
  • 或者直接背格雷码的公式?吧:
class Solution:def grayCode(self, n: int) -> List[int]:return [i ^ i >> 1  for i in range(1 << n)]

94. Binary Tree Inorder Traversal 2行

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution:def inorderTraversal(self, root: TreeNode) -> List[int]:f = self.inorderTraversalreturn f(root.left) + [root.val] + f(root.right) if root else []
class Solution:def inorderTraversal(self, root: TreeNode) -> List[int]:r, stack = [], []while True:while root:stack.append(root)root = root.leftif not stack:return rnode = stack.pop()r.append(node.val)root = node.rightreturn r

104. Maximum Depth of Binary Tree 1行

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution:def maxDepth(self, root: TreeNode) -> int:return max(map(self.maxDepth,(root.left, root.right))) + 1 if root else 0

121. Best Time to Buy and Sell Stock 2行

class Solution:def maxProfit(self, prices: List[int]) -> int:from functools import reducereturn reduce(lambda r, p: (max(r[0], p-r[1]), min(r[1], p)), prices, (0, float('inf')))[0]
class Solution:def maxProfit(self, prices: List[int]) -> int:r, m = 0, float('inf')for p in prices:r, m = max(r, p - m), min(m, p)return r

122. Best Time to Buy and Sell Stock II 2行

class Solution:def maxProfit(self, prices: List[int]) -> int:return sum(b - a for a, b in zip(prices, prices[1:]) if b > a)

124. Binary Tree Maximum Path Sum 4行

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution:def maxPathSum(self, root: TreeNode, ok=True) -> int:if not root: return 0l, r = self.maxPathSum(root.left, False), self.maxPathSum(root.right, False)self.max = max(getattr(self, 'max', float('-inf')), l + root.val + r)return self.max if ok else max(root.val + max(l, r), 0)

136. Single Number 2行

class Solution:def singleNumber(self, nums: List[int]) -> int:from functools import reducereturn reduce(int.__xor__, nums)

141. Linked List Cycle 2行

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution(object):def hasCycle(self, head):""":type head: ListNode:rtype: bool"""while head and head.val != None: head.val, head = None, head.nextreturn head != None
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution(object):def hasCycle(self, head):slow = fast = headwhile fast and fast.next:fast = fast.next.nextslow = slow.nextif slow == fast:return Truereturn False

142. Linked List Cycle II 5行

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution(object):def detectCycle(self, head):""":type head: ListNode:rtype: ListNode"""s = {None}while head not in s:s.add(head)head = head.nextreturn head

146. LRU Cache 7行

class LRUCache(object):def __init__(self, capacity):self.od, self.cap = collections.OrderedDict(), capacitydef get(self, key):if key not in self.od: return -1self.od.move_to_end(key)return self.od[key]def put(self, key, value):if key in self.od: del self.od[key]elif len(self.od) == self.cap: self.od.popitem(False)self.od[key] = value# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

148. Sort List 10行

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def sortList(self, head: ListNode) -> ListNode:if not (head and head.next): return headpre, slow, fast = None, head, headwhile fast and fast.next: pre, slow, fast = slow, slow.next, fast.next.nextpre.next = Nonereturn self.mergeTwoLists(*map(self.sortList, (head, slow)))def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:if l1 and l2:if l1.val > l2.val: l1, l2 = l2, l1l1.next = self.mergeTwoLists(l1.next, l2)return l1 or l2

155. Min Stack 每个1行

class MinStack:def __init__(self):self.data = [(None, float('inf'))]def push(self, x: 'int') -> 'None':self.data.append((x, min(x, self.data[-1][1])))def pop(self) -> 'None':if len(self.data) > 1: self.data.pop()def top(self) -> 'int':return self.data[-1][0]def getMin(self) -> 'int':return self.data[-1][1]# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

160. Intersection of Two Linked Lists 3行

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution(object):def getIntersectionNode(self, headA, headB):""":type head1, head1: ListNode:rtype: ListNode"""a, b = (headA, headB) if headA and headB else (None, None)while a != b: a, b = not a and headB or a.next, not b and headA or b.nextreturn a

162. Find Peak Element 2行

class Solution:def findPeakElement(self, nums: List[int]) -> int:self.__class__.__getitem__ = lambda self, i: i and nums[i - 1] > nums[i]return bisect.bisect_left(self, True, 0, len(nums)) - 1

169. Majority Element 1行

class Solution:def majorityElement(self, nums: List[int]) -> int:return sorted(nums)[len(nums) // 2]

198. House Robber 2行

class Solution:def rob(self, nums: List[int]) -> int:from functools import reducereturn reduce(lambda r, n: (max(r[0], n + r[1]), r[0]), nums, (0, 0))[0]
class Solution:def rob(self, nums: List[int]) -> int:last, now = 0, 0for i in nums:last, now = now, max(last + i, now)return now

200. Number of Islands 7行

class Solution(object):def numIslands(self, grid):def sink(i, j):if 0 <= i < len(grid) and 0 <= j < len(grid[i]) and int(grid[i][j]):grid[i][j] = '0'for i, j in zip((i, i+1, i, i-1), (j+1, j, j-1, j)): sink(i, j)return 1return 0return sum(sink(i, j) for i in range(len(grid)) for j in range(len(grid[i])))

206. Reverse Linked List 2行

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def reverseList(self, head: ListNode, tail=None) -> ListNode:if head: head.next, tail, head = tail, head, head.nextreturn self.reverseList(head, tail) if head else tail
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def reverseList(self, head: ListNode) -> ListNode:p = Nonewhile head: head.next, p, head = p, head, head.nextreturn p

215. Kth Largest Element in an Array 1行

class Solution:def findKthLargest(self, nums: List[int], k: int) -> int:return sorted(nums)[-k]

217. Contains Duplicate 1行

class Solution:def containsDuplicate(self, nums: List[int]) -> bool:return len(nums) != len(set(nums))

230. Kth Smallest Element in a BST 3行

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution:def kthSmallest(self, root, k):from itertools import chain, islicedef gen(x): yield from chain(gen(x.left), [x.val], gen(x.right)) if x else ()return next(islice(gen(root), k - 1, k))

231. 2的幂 1行

class Solution:def isPowerOfTwo(self, n: int) -> bool:""":type n: int:rtype: bool"""return n > 0 and n & n - 1 == 0

235. Lowest Common Ancestor of a Binary Search Tree 2行

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution:def lowestCommonAncestor(self, root, p, q):while (root.val - p.val) * (root.val - q.val) > 0: root = (root.left, root.right)[p.val > root.val]return root

236. Lowest Common Ancestor of a Binary Tree 2行

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution:def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':l, r = map(lambda x: x and self.lowestCommonAncestor(x, p, q), (root.left, root.right))return (root in (p, q) or l and r) and root or l or r

237. Delete Node in a Linked List 1行

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def deleteNode(self, node):""":type node: ListNode:rtype: void Do not return anything, modify node in-place instead."""node.val, node.next = node.next.val, node.next.next

238. Product of Array Except Self 5行

class Solution:def productExceptSelf(self, nums: List[int]) -> List[int]:res, l, r = [1] * len(nums), 1, 1for i, j in zip(range(len(nums)), reversed(range(len(nums)))):res[i], l = res[i] * l, l * nums[i]res[j], r = res[j] * r, r * nums[j]return res

240. Search a 2D Matrix II 1行

class Solution:def searchMatrix(self, matrix, target):""":type matrix: List[List[int]]:type target: int:rtype: bool"""return any(target in row for row in matrix)
  • 以下为 O(m+n) 解法:

    class Solution:def searchMatrix(self, matrix, target):""":type matrix: List[List[int]]:type target: int:rtype: bool"""j = -1for row in matrix:while j > -len(row) and row[j] > target:j -= 1if row and row[j] == target:return Truereturn False
    
    • 从矩阵右上角开始,若值比 target 大则证明这一列的值都比 target 大,继续搜索前面的列;若比 target 小说明 target 可能在后面的行中,进入下一行

268. Missing Number 1行

class Solution:def missingNumber(self, nums: List[int]) -> int:return int(len(nums) * (len(nums) + 1) / 2 - sum(nums))

283. Move Zeroes 1行

class Solution:def moveZeroes(self, nums: List[int]) -> None:"""Do not return anything, modify nums in-place instead."""nums.sort(key=bool, reverse=True)
class Solution:def moveZeroes(self, nums: List[int]) -> None:"""Do not return anything, modify nums in-place instead."""i = 0for i, n in enumerate(filter(lambda x: x, nums)):nums[i] = nfor i in range(i + 1, len(nums)):nums[i] = 0

292. Nim Game 1行

class Solution:def canWinNim(self, n: int) -> bool:return bool(n % 4)

328. Odd Even Linked List 6行

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def oddEvenList(self, head: ListNode) -> ListNode:if not head or not head.next: return headr, odd, p, head = head, head, head.next, head.next.nextwhile head:odd.next, head.next, p.next = head, odd.next, head.nextp, odd, head = p.next, head, p.next and p.next.nextreturn r

344. Reverse String 1行

class Solution:def reverseString(self, s: List[str]) -> None:"""Do not return anything, modify s in-place instead."""s.reverse()

347. Top K Frequent Elements 1行

class Solution:def topKFrequent(self, nums: List[int], k: int) -> List[int]:return [k for k, v in collections.Counter(nums).most_common(k)]
class Solution:def topKFrequent(self, nums: List[int], k: int) -> List[int]:d = {}for n in nums:d[n] = d.get(n, 0) + 1return sorted(d.keys(), key=d.get)[-k:]

367. Valid Perfect Square 4行

class Solution:def isPerfectSquare(self, num: int) -> bool:r = numwhile r * r > num:r = (r + num / r) // 2return r * r == num

412. Fizz Buzz 1行

class Solution:def fizzBuzz(self, n):return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]

414. Third Maximum Number 3行

class Solution:def thirdMax(self, nums: List[int]) -> int:nums = set(nums)for _ in range((2, 0)[len(nums) < 3]): nums.remove(max(nums))return max(nums)

448. Find All Numbers Disappeared in an Array 1行

class Solution:def findDisappearedNumbers(self, nums: List[int]) -> List[int]:s = set(nums)return [i for i in range(1, len(nums) + 1) if i not in s]

461. Hamming Distance 1行

class Solution:def hammingDistance(self, x: int, y: int) -> int:return bin(x ^ y).count('1')

557. Reverse Words in a String III 1行

class Solution:def reverseWords(self, s: str) -> str:return ' '.join(s.split(' ')[::-1])[::-1]

752. Open the Lock 11行

class Solution:def openLock(self, deadends: List[str], target: str) -> int:if '0000' in deadends: return -1deadends, q = set(deadends), [('0000', 0)]while q:node, step = q.pop(0)for i, add in zip([*range(4)] * 2, [1] * 4 + [-1] * 4):cur = node[:i] + str((int(node[i]) + add) % 10) + node[i+1:]if cur == target: return step + 1if not cur in deadends:q.append((cur, step + 1))deadends.add(cur)return -1

771. Jewels and Stones 1行

class Solution:def numJewelsInStones(self, J: str, S: str) -> int:return sum(S.count(i) for i in J)

867. Transpose Matrix 1行

class Solution:def transpose(self, A: List[List[int]]) -> List[List[int]]:return [*zip(*A)]

938. Range Sum of BST 1行

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution:def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:return root and root.val * (L <= root.val <= R) + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R) or 0

953. Verifying an Alien Dictionary 1行

class Solution(object):def isAlienSorted(self, words, order):return words == sorted(words, key=lambda w: [order.index(x) for x in w])
  • 充分利用 python 序列比较的特点,sorted 的参数 key 可传入一个函数,sorted 函数会将每个元素作为输入,输入到 key 函数并获得返回值,整个序列将按此值的大小来排序。此处 key 函数为lambda w: [order.index(x) for x in w],其为words中每个单词 word 返回一个 list,list 中每个元素为单词中字母 x 在 order 中的索引。比如当 order 为 ‘abcde……’ 时,单词 ‘cab’ 将返回 [3, 2, 1]。关于俩个 list 的大小比较,服从 python 序列比较的特性,请参考官方文档教程 5.8 节内容。

  • 另外一个通用的方法是简单的数学计算,给每个单词赋予一个数字然后排序对比和原来的数组是否一致即可,每个字母的价值按字母表顺序,第几个就代表几,每进一位需要*10^-2避免冲突,比如字母表是abcde……,单词 cab 的价值就是 3 * 1 + 1 * 0.01 + 2 * 0.0001,价值越小的单词位置应该越靠前

    class Solution:def isAlienSorted(self, words: List[str], order: str) -> bool:d = {c: i + 1 for i, c in enumerate(order)}return sorted(words, key=lambda x: sum(d[c] * 10**(-2 * i) for i, c in enumerate(x))) == words
    

973. K Closest Points to Origin 1行

class Solution:def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:return sorted(points, key=lambda x: x[0]**2 + x[1]**2)[:K]

专题探索

以上是一张互联网公司面试中经常考察的问题类型总结的思维导图,此栏目将根据 LeetCode 中文版探索板块给出的路线制作题解,各专栏将尽力覆盖各大知识要点并总结知识点和套路。相比于题库解析部分追求代码的绝对精简,本专题追求以高可读性呈现各大专题的常规思路,为后续的题库解析部分做铺垫。俩部分题目可能重复,但专题部分会有更详细的解析,且可能运用不同解法。

数据结构,说难也不难

队列 & 栈

队列:先入先出的数据结构

622. 设计循环队列

class MyCircularQueue:def __init__(self, k: int):"""Initialize your data structure here. Set the size of the queue to be k."""self.size = kself.data = []def enQueue(self, value: int) -> bool:"""Insert an element into the circular queue. Return true if the operation is successful."""if self.isFull():return Falseself.data.append(value)return Truedef deQueue(self) -> bool:"""Delete an element from the circular queue. Return true if the operation is successful."""if self.isEmpty():return Falseself.data.pop(0)return Truedef Front(self) -> int:"""Get the front item from the queue."""if self.isEmpty():return -1return self.data[0]def Rear(self) -> int:"""Get the last item from the queue."""if self.isEmpty():return -1return self.data[-1]def isEmpty(self) -> bool:"""Checks whether the circular queue is empty or not."""return not self.datadef isFull(self) -> bool:"""Checks whether the circular queue is full or not."""return len(self.data) == self.size# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()

队列和广度优先搜索

200. 岛屿的个数

from queue import Queueclass Solution(object):def numIslands(self, grid):try:r = 0; m = len(grid); n = len(grid[0])around = ((0, 1), (1, 0), (0, -1), (-1, 0))except:return 0for i in range(m):for j in range(n):if int(grid[i][j]):r += 1#---------------------------BFS 开始-----------------------------# 把根节点投入队列q = Queue()q.put((i, j))# 开始循环while not q.empty():# 取出还未沉没的陆地节点并沉没陆地(防止下次遍历到的时候再算一遍)x, y = q.get()if int(grid[x][y]):grid[x][y] = '0'# 放入周围的陆地节点for a, b in around:a += x; b += y;if 0 <= a < m and 0 <= b < n and int(grid[a][b]):q.put((a, b))#----------------------------------------------------------------return r

752. 打开转盘锁

from queue import Queueclass Solution:def openLock(self, deadends: List[str], target: str) -> int:deadends = set(deadends) # in 操作在set中时间复杂度为O(1)if '0000' in deadends:return -1# -------------------------------BFS 开始----------------------------------# 初始化根节点q = Queue()q.put(('0000', 0)) # (当前节点值,转动步数)# 开始循环队列while not q.empty():# 取出一个节点node, step = q.get()# 放入周围节点for i in range(4):for add in (1, -1):cur = node[:i] + str((int(node[i]) + add) % 10) + node[i+1:]if cur == target:return step + 1if not cur in deadends:q.put((cur, step + 1))deadends.add(cur) # 避免重复搜索# -------------------------------------------------------------------------return -1

解法汇总贡献者

注:此处贡献名单仅代表汇总搜集贡献,不代表全部原创,欢迎所有更短的解法?

  • Knife丶[QQ1272068154 微信ly18597591102]
  • zdylzdyl

Leet Code 力扣 - - 最短最优雅python解法带解析汇总相关推荐

  1. 力扣- - 最短回文串(KMP算法)

    力扣- - 最短回文串(KMP算法) 文章目录 力扣- - 最短回文串(KMP算法) 一.题目描述 二.分析之KMP算法 1.暴力法 2.KMP算法 3.next数组求法1:暴力查找最长的前后缀 4. ...

  2. 力扣416 二维数组解法

    力扣416题. 动态规划的二维数组解法,虽然耗时耗空间,但是花了俩小时明白了为什么for循环不能互换,使用顺序遍历和倒叙遍历的原因,以及dp数组更迭方式.印象深刻.因为我看的书上只用了滚动数组方法,没 ...

  3. 力扣刷题之python报错SyntaxError: invalid syntax ^

    本人力扣小白,第一天刷题一直出错SyntaxError: invalid syntax,,,, 解决办法: 检查语言选项是否为python3,选python的话,默认为python2,如图 然后就解决 ...

  4. 力扣 - 独一无二的出现次数 python解

    from collections import Counter class Solution:def uniqueOccurrences(self, arr: List[int]) -> boo ...

  5. leetcode力扣刷题系列python——2、两数相加

    题目: 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表示 ...

  6. 力扣.765情侣牵手——python

    我们先了解一下题意求,只要情侣在左右都可以,而且求数字 x 的对象时用到了一个技巧,x 的对象是x ^ 1.解释如下: 当 x 是偶数,则其二进制的末尾是 0,所以 x ^ 1 将其二进制的末尾改成 ...

  7. 力扣35. 搜索插入位置python实现

    35. 搜索插入位置 一.问题描述 二.算法思想   题目中的数组是排好序的,从头开始遍历,当发现列表中元素的值与target相等时返回该元素在列表中的位置i,否则继续查找,当发现列表中的元素比tar ...

  8. 力扣简单题合集(带答案)

    1.给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能使用两遍 ...

  9. 力扣 -----最小绝对值(JavaScript解法)

    一.题目描述 二.示例 三.解题思路 先进行一个排序,然后使用双指针,依次进行比较,将比较的值进行存储,最小值改变的话,数组置空,最小值改变,如果和最小值相等的话直接push.我刚开始写的排序是 四. ...

最新文章

  1. 2016阅读总结——我的问题就是读书太少
  2. Spring和MyBatis的整合
  3. 重构-打造爱因斯坦谜题最快算法
  4. Android 中基本图像绘制
  5. 文献记录(part102)--Two-phase clustering process for outliers detection
  6. c语言分组求和函数,R语言 实现data.frame 分组计数、求和等
  7. zookeeper学习之原理
  8. 国家开放大学2021春1378管理英语3题目
  9. 前端学习(1922)vue之电商管理系统电商系统之渲染角色数据
  10. leetcode —— 6. Z 字形变换
  11. 框架学习八:二维码(Zxing)
  12. 使用ASP.NET Web API构建Restful API
  13. ftp pam mysql_ftp+pam基于mysql的认证
  14. 使用Python合成gif动图
  15. 设计一个移动应用的本地缓存机制(转)
  16. 杨辉三角形c语言程序
  17. 大型石油公司联手银行推出能源商品交易区块链平台
  18. 大数据平台核心架构图鉴,建议收藏!
  19. python实现黄金分割法确定极小点
  20. php 更改发送ip,PHP重新启动路由器以更改IP地址程序

热门文章

  1. 顺时针(逆时针)填充矩阵
  2. 如何用键盘打开设备管理器里计算机的属性,技巧:在Windows10系统中使用键盘打开设备管理器的三种方法...
  3. 自己用的一些觉得不错的软件
  4. Li‘s 影像组学视频学习笔记(14)-特征权重做图及美化
  5. 数加加众包深耕AI第8年,苹果加码人工智能和机器学习
  6. 分享25个很棒的网页设计教程和资源网站
  7. 制作支持View,图片轮播的Banner
  8. 中国移动宽带测试用哪个软件,中国移动评测四大类手机应用APP 看完你就知道5G和4G网络差距在哪儿...
  9. Kotlin ?.let 、!! 、?:等运算符的使用
  10. 第四课 尚硅谷Scala语言学习-面向对象