while left < right: current = numbers[left] + numbers[right] if current == target: return [left + 1, right + 1] elif current < target: left += 1 else: right -= 1 return [-1, -1]
for right, char inenumerate(s): if char in char_index and char_index[char] >= left: left = char_index[char] + 1 char_index[char] = right max_len = max(max_len, right - left + 1)
for num in nums: current_sum += num if current_sum - k in prefix_sum: count += prefix_sum[current_sum - k] prefix_sum[current_sum] = prefix_sum.get(current_sum, 0) + 1
return count
链表
基础操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classListNode: def__init__(self, val=0, next=None): self.val = val self.next = next
defreverse_list(head: ListNode) -> ListNode: """反转链表""" prev = None current = head
while current: next_node = current.next current.next = prev prev = current current = next_node
defhas_cycle(head: ListNode) -> bool: """检测环形链表""" slow = fast = head
while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: returnTrue
returnFalse
deffind_middle(head: ListNode) -> ListNode: """找到链表中点""" slow = fast = head
while fast and fast.next: slow = slow.next fast = fast.next.next
return slow
栈与队列
单调栈
1 2 3 4 5 6 7 8 9 10 11 12 13
defdaily_temperatures(temperatures: list[int]) -> list[int]: """每日温度:距离下一次更高温度的天数""" n = len(temperatures) answer = [0] * n stack = [] # 单调递减栈,存索引
for i, temp inenumerate(temperatures): while stack and temperatures[stack[-1]] < temp: prev_idx = stack.pop() answer[prev_idx] = i - prev_idx stack.append(i)
while current or stack: while current: stack.append(current) current = current.left current = stack.pop() result.append(current.val) current = current.right
while queue: level = [] for _ inrange(len(queue)): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level)