1. 两数之和
题目 :在数组中找到两个数,它们的和等于目标值,返回下标
案例 :给定数组 nums = [2,7,11,15],目标值 target = 9
效果 :2 + 7 = 9 → 返回 [0, 1]
核心:用目标值减去当前数,看差值是否在剩余数组中
python
nums = [2, 7, 11, 15]
target = 9
for i in range(len(nums)):
res = target - nums[i] # 需要的另一个数
if res in nums[i + 1:]: # 在剩余部分查找
# index(res)返回在切片中的位置,加上偏移量得到原数组下标
print(i, nums[i + 1:].index(res) + i + 1)
2. 字母异位词分组
题目 :将字母组成相同的单词分到同一组
案例 :输入 strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
效果 :[["bat"], ["nat","tan"], ["ate","eat","tea"]]
核心:排序后的字符串作为字典的键
python
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
sorted_dict = {}
for s in strs:
sorted_strs = ''.join(sorted(s)) # 排序后作为唯一标识
if sorted_strs not in sorted_dict:
sorted_dict[sorted_strs] = [s] # 新建列表
else:
sorted_dict[sorted_strs].append(s) # 追加到已有列表
print(list(sorted_dict.values()))
3. 最长连续序列
题目 :找出数字连续的最长序列长度(不要求在原数组中连续)
案例 :输入 nums = [0,3,7,2,5,8,4,6,0,1]
效果 :0,1,2,3,4,5,6,7,8 连续 → 长度 9
核心:只从每个连续序列的第一个数开始计数
python
nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
nums1 = set(sorted(nums)) # 去重并排序
array = []
for i in nums1:
if i - 1 not in nums1: # 找到连续序列的起点
count = 1
while i + 1 in nums1: # 向后找连续的数
count += 1
i += 1
array.append(count)
print(max(array))
4. 相交链表
题目 :找到两个链表相交的起始节点,没有则返回null
案例 :
A: a1 → a2 → a3 → a4
↓
c3 → c4
↑
B: b1 → b2 → b3
效果 :返回 c3
核心:浪漫相遇 - 两个指针走完自己的路再走对方的路
python
def get_cross_node(headA, headB):
A, B = headA, headB
while A != B: # 相遇时退出
# A走自己的路,到头了就走B的路
A = A.next if A else headB
# B走自己的路,到头了就走A的路
B = B.next if B else headA
return A # 要么相交点,要么null
为什么浪漫:就像两个人,走过彼此来时的路,最终相遇
5. 反转链表
题目 :反转单链表
案例 :原链表 1 → 2 → 3 → None
效果 :None ← 1 ← 2 ← 3
核心:三个指针 - cur当前节点,pre前一个节点,next下一个节点
python
def reverse_list(head):
cur = head
pre = None
while cur:
next = cur.next # 先保存下一个节点
cur.next = pre # 当前节点指向前一个节点
pre = cur # pre移动到当前节点
cur = next # cur移动到下一个节点
return pre # pre就是新头节点
6. 回文链表
题目 :判断链表是否正反读都一样
案例 :链表 1 → 2 → 2 → 1
效果 :正着读1221,反着读1221 → true
核心:转为数组,比较数组和它的反转
python
def is_palindrome(head):
vals = []
cur = head
while cur: # 遍历链表存入数组
vals.append(cur.val)
cur = cur.next
return vals == vals[::-1] # 比较数组和它的反转
7. 环形链表
题目 :判断链表中是否有环
案例 :链表 1 → 2 → 3 → 4 → 5 → 2(指向节点2)
效果 :有环 → true
核心:快慢指针 - 龟兔赛跑,兔子绕圈追上乌龟
python
def has_cycle(head):
slow = fast = head
while fast and fast.next: # 快指针能走两步的前提
slow = slow.next # 慢指针走一步
fast = fast.next.next # 快指针走两步
if slow == fast: # 相遇则有环
return True
return False # 走到头则无环
关键:每走一步,快指针会追上慢指针一步
8. 合并两个有序链表
题目 :合并两个升序链表为一个新升序链表
案例 :l1 = 1→2→4,l2 = 1→3→4
效果 :1→1→2→3→4→4
核心:虚拟头节点 + 双指针比较
python
def merge_two_lists(l1, l2):
dummy = cur = ListNode(0) # 虚拟头节点,简化操作
# 两个链表都还有节点时,比较大小
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
# 处理剩余节点(其中一个链表已空)
if l1:
cur.next = l1
if l2:
cur.next = l2
return dummy.next # 跳过虚拟头节点