1.1. 两数之和
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
idx = {} # hash表(dict)
for j, x in enumerate(nums):
if target - x in idx: # 默认是查询key的集合是否包含target-x
return [idx[target -x], j] # 返回两个数字的下标
idx[x] = j # key -> 数值num; val -> 数值的下标index
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = defaultdict(list) # 若key不在字典中,则自动插入一个空列表
for s in strs:
sorted_s = ''.join(sorted(s)) # 把s排序,作为hash表的key
d[sorted_s].append(s) # value就存放原来的、未排序的字符串
return list(d.values()) # 返回res(分组后的结果)
3. 128. 最长连续序列
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
st = set(nums)
res, m = 0, len(st)
for x in st: # 遍历哈希集合
if x - 1 in st: continue # 如果x不是序列的起点,直接跳过
y = x + 1
while y in st: # 不断查找下一个数是否在hash集合中
y += 1
res = max(res, y - x) # 循环结束后, y - 1是最后一个在哈希集合中的数
if res * 2 >= m: break # res不可能变得更大
return res
4. 283. 移动零
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
# 核心思路:把 0 视作空位。我们要把所有非零元素都移到数组左边的空位上,并保证非零元素的顺序不变。
i = 0 # i指向最左边的空位, j指向可能需要交换的数字
for j in range(len(nums)):
if nums[j]:
nums[j], nums[i] = nums[i], nums[j]
i += 1
class Solution:
def maxArea(self, height: List[int]) -> int:
res = left = 0
right = len(height - 1) - 1
while left < right:
area = (right - left) * min(height[left], height[right])
res = max(res, area)
if height[left] < height[right]: # 短板效应驱使移动短的板去移动,width--,只能找到更大木板才有可能让area更大
left += 1
else:
right -= 1
return res
6. 相交链表
核心口诀:“走过你来时的路,我们终会相遇”。
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
if not headA or not headB: return None
p, q = headA, headB
while p is not q: # 只要还没相遇(or还没一起走到尽头->None),就继续走
p = p.next if p else headB
q = q.next if q else headA
return p # p要么是相交结点,要么是None(不香蕉)
7. 反转链表
核心口诀:“保存下一步,回头握手,一起往下走”。
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre, cur = None, head
while cur:
nxt = cur.next # step1: 保存下一步(一会断开了)
# step2: 回头握手
cur.next = pre # 相当于:把cur插在pre链表的前面(头插法)
# 一起往下走
pre = cur; cur = nxt
return pre # 最后状态是cur为None, 那么pre就是最新的头结点!
8.
976

被折叠的 条评论
为什么被折叠?



