Kodewick
开始学 →
题型与套路:哈希表21 / 52

题型与套路:哈希表

第 21 课,共 52 课 · 第 4 部分 · 哈希表:dict 和 set · 约 20 分钟

这一课是第 3 章的复习,讲哈希表的三个套路:用 dict 记住见过的(一遍做完两数之和)、用 Counter 计数、用 defaultdict(list) 分组,都把两两比较的 O(n²) 降到 O(n)。

两层循环两两比较,是最常见的 O(n²):两数之和、找重复、数每个词出现几次、把异位词放到一组。哈希表把「和前面的每一个比」换成「查一下见过没有」,平均 O(1),整题就从 O(n²) 降到 O(n)。n = 10 万时,两两比较是 50 亿次,查表是 10 万次。面试里的哈希表题大多落在三个套路上:记住见过的(dict:值 → 下标)、数个数(Counter)、按键分组(defaultdict(list))。

套路一:记住见过的

两数之和:在没排序的 nums 里找两个数,和等于 target,返回下标。一边往后走,一边把见过的数记进 dict(值 → 下标)。走到 x 时,要的另一半是 target - x:它要是在前面出现过,dict 里一查就有。

ix要找 13 − xseen 里有吗然后
067没有seen = {6: 0}
1112没有seen = {6: 0, 1: 1}
294没有seen = {6: 0, 1: 1, 9: 2}
349有,下标 2返回 (2, 3)
nums = [6, 1, 9, 4, 8],target = 13:每一步先查 13 − x 见过没有,没有再把 x 记下

两种写法各数一数(400 个数,答案是最后两个):

main.py
1def two_sum_brute(nums, target):2    looks = 03    for i in range(len(nums)):4        for j in range(i + 1, len(nums)):5            looks += 16            if nums[i] + nums[j] == target:7                return (i, j), looks8    return None, looks9 10def two_sum(nums, target):11    looks = 012    seen = {}                           # 值 -> 下标13    for i, x in enumerate(nums):14        looks += 115        if target - x in seen:16            return (seen[target - x], i), looks17        seen[x] = i18    return None, looks19 20nums = [(i * 7) % 398 * 2 for i in range(398)] + [1001, 1003]21print(two_sum_brute(nums, 2004))22print(two_sum(nums, 2004))23print(two_sum([6, 1, 9, 4, 8], 13))
输出
((398, 399), 79800)
((398, 399), 400)
((2, 3), 4)

暴力看了 79800 对,dict 只走了 400 步。顺序很要紧:先查,再记。先记再查,x 会和它自己配上:[3] 找 6,会错误地返回 (0, 0)。

猜输出猜错也没关系

有重复的数时,打印什么?

1def two_sum(nums, target):2    seen = {}3    for i, x in enumerate(nums):4        if target - x in seen:5            return seen[target - x], i6        seen[x] = i7    return None8 9print(two_sum([3, 3], 6), two_sum([3], 6), two_sum([1, 3, 3], 6))

同一个套路还能做:判断有没有重复(set 记见过的)、最长不重复子串(dict 记每个字符上次出现的位置)、和为 k 的子数组(dict 记前缀和出现过几次)。

单选

照这一关的做法(先查 8 − x,再记下 x),在 nums = [1, 6, 2, 5, 3] 里找和为 8 的两个数。返回哪一对下标?

单选

用 dict 一遍做两数之和,时间和额外空间各是多少?

练习 1

两数之和

补全 two_sum(nums, target):nums 没排序,返回和为 target 的两个数的下标 (i, j),i < j;没有就返回 None。只走一遍,用 dict 记见过的数。

要显示
(0, 1)
(1, 2)
(0, 1)
None
exercise1.py
1def two_sum(nums, target):2    seen = {}                # 值 -> 下标3    # 先查 target - x 见过没有,再把 x 记下4    return None5 6print(two_sum([2, 7, 11, 15], 9))7print(two_sum([3, 2, 4], 6))8print(two_sum([3, 3], 6))9print(two_sum([1, 2], 7))
输出
点「运行」或按 Ctrl+Enter

套路二:数个数

「每个词出现几次」:dict 里键是词,值是次数。手写就是 counts[w] = counts.get(w, 0) + 1:

读到counts
the{'the': 1}
cat{'the': 1, 'cat': 1}
the{'the': 2, 'cat': 1}
hat{'the': 2, 'cat': 1, 'hat': 1}
the{'the': 3, 'cat': 1, 'hat': 1}
数 "the cat the hat the":每读一个词,它的次数加 1,第一次见到就从 0 开始

collections.Counter 就是一个专门数数的 dict:传一串东西进去就数好了,没出现过的键是 0(不会 KeyError),most_common(k) 给出最多的 k 个。

main.py
1from collections import Counter2 3text = "the cat and the hat and the bat sat on the mat"4words = text.split()5 6counts = {}7for w in words:8    counts[w] = counts.get(w, 0) + 19print(counts["the"], counts["and"])10 11c = Counter(words)12print(c["the"], c["dog"])13print(c.most_common(3))14print(sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))[:3])
输出
4 2
4 0
[('the', 4), ('and', 2), ('cat', 1)]
[('the', 4), ('and', 2), ('bat', 1)]

most_common 次数相同时按第一次出现的顺序排(只出现 1 次的词里 cat 最先出现;按字母序该是 bat)。题目要求「次数一样按字母序」,就自己用 sorted 排:key 是 (-次数, 词),次数从大到小,同次数再按词从小到大。

异位词(字母一样、顺序不同,如 listen 和 silent):两个词的字母各数一遍,比两个 Counter 相等就行,O(n)。排序再比也对,但是 O(n log n)。

main.py
1from collections import Counter2 3def is_anagram(a, b):4    return Counter(a) == Counter(b)5 6print(is_anagram("listen", "silent"), is_anagram("aab", "abb"))7print(sorted("listen") == sorted("silent"))8print(sorted(Counter("aab").items()))
输出
True False
True
[('a', 2), ('b', 1)]
猜输出猜错也没关系

用 Counter 数 「banana」 的字母。打印什么?

1from collections import Counter2 3c = Counter("banana")4print(c["a"], c["z"], c.most_common(2))
单选

判断两个长度为 n 的词是不是异位词,用 Counter(a) == Counter(b) 和用 sorted(a) == sorted(b),时间各是多少?

练习 2

前 k 个高频词

补全 top_k(words, k):返回出现最多的 k 个 (词, 次数),次数从多到少;次数一样时按词的字母序。注意 most_common 同次数时按出现顺序排,不符合要求。

要显示
[('d', 4), ('a', 3)]
[('x', 2), ('y', 2)]
[('x', 2), ('y', 2), ('z', 1)]
exercise2.py
1from collections import Counter2 3def top_k(words, k):4    c = Counter(words)5    # 按 (-次数, 词) 排序,取前 k 个6    return c.most_common(k)7 8print(top_k("b a c a b a d d d d".split(), 2))9print(top_k("y x y x z".split(), 2))10print(top_k("y x y x z".split(), 3))
输出
点「运行」或按 Ctrl+Enter

套路三:按键分组

把异位词分到一组:eat、tea、ate 一组,tan、nat 一组,bat 自己一组。关键是算出一个键,让同一组的词算出来一样:把字母排序,eat、tea、ate 都变成 aet。然后用 defaultdict(list) 按这个键往桶里放:

"".join(sorted(w))aetantabt

按排好序的字母分组:键一样的词进同一个桶,每个桶就是一组
main.py
1from collections import defaultdict2 3words = ["eat", "tea", "tan", "ate", "nat", "bat"]4groups = defaultdict(list)5for w in words:6    key = "".join(sorted(w))7    groups[key].append(w)8print(list(groups.values()))9print(groups["aet"], len(groups))10 11def letter_key(w):12    counts = [0] * 2613    for ch in w:14        counts[ord(ch) - ord("a")] += 115    return tuple(counts)            # tuple 才能当键16 17groups2 = defaultdict(list)18for w in words:19    groups2[letter_key(w)].append(w)20print(list(groups2.values()))
输出
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
['eat', 'tea', 'ate'] 3
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

defaultdict(list) 第一次碰到一个键时自动放进一个空 list,不用先写 if key not in groups。第二种键是 26 个字母的计数,算一次是 O(k),不用排序;它必须是 tuple,list 不能当键(这一章第一课)。

套路dict 里存什么典型题时间
记住见过的值 → 下标(或 set 只记值)两数之和、有没有重复、最长不重复子串O(n)
数个数东西 → 次数(Counter)前 k 个高频、异位词、第一个不重复的字符O(n)
按键分组算出的键 → list异位词分组、按某个属性归类O(n) × 算键

面试里: 先说暴力 O(n²),再说「用 dict 记住见过的,换成 O(n) 时间、O(n) 空间」:这是一次用空间换时间。分组题的关键是一句话说清「什么样的东西该算出一样的键」。

单选

给异位词分组,下面哪个能当 groups[...] 的键?

练习 3

异位词分组

补全 group_anagrams(words):把异位词分到一组。为了输出固定,每组里的词按字母序排,各组再按第一个词排。

要显示
[['ate', 'eat', 'tea'], ['bat'], ['nat', 'tan']]
[['a']]
[]
exercise3.py
1from collections import defaultdict2 3def group_anagrams(words):4    groups = defaultdict(list)5    # 键:把词的字母排好序再拼起来6    return []7 8print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))9print(group_anagrams(["a"]))10print(group_anagrams([]))
输出
点「运行」或按 Ctrl+Enter

工作里这样写

三个套路都有现成的工具:

main.py
1from collections import Counter, defaultdict2 3c = Counter()4c.update(["a", "b", "a"])5c.update(["a"])6print(c["a"], c.most_common(1))7 8stock = Counter({"apple": 3, "pear": 1})9stock.subtract({"apple": 1})10print(sorted(stock.items()))11 12tags = defaultdict(set)13for user, tag in [("amy", "py"), ("bob", "go"), ("amy", "py"), ("amy", "sql")]:14    tags[user].add(tag)15print(sorted(tags["amy"]), len(tags))16 17d = {}18d.setdefault("k", []).append(1)19print(d, d.get("x", 0))
输出
3 [('a', 3)]
[('apple', 2), ('pear', 1)]
['py', 'sql'] 2
{'k': [1]} 0
  • Counter(xs):数个数;c[x] 没有就是 0;most_common(k) 内部用堆,O(n log k);c.update(...) 接着数。
  • defaultdict(list)、defaultdict(set)、defaultdict(int):分组、去重分组、计数。
  • 普通 dict 也行:d.get(k, 0) + 1、d.setdefault(k, []).append(v)。
  • 打印字符串组成的 set 或者按 set 的顺序输出,结果每次运行都可能不同:先 sorted。
猜输出猜错也没关系

defaultdict(int) 数字母,最后再看一个没出现过的字母。打印什么?

1from collections import defaultdict2 3d = defaultdict(int)4for ch in "hello":5    d[ch] += 16print(d["l"], d["z"], len(d))

小结

这一课带走

哈希表的三个套路

  • 记住见过的:dict 存值 → 下标,先查 target − x 再记 x,一遍 O(n)
  • 数个数:Counter,没有的键是 0;同次数要字母序就 sorted(key=(-次数, 词))
  • 按键分组:同组算出同一个键(排序后的字母、计数 tuple),defaultdict(list) 往里放
  • 都是用 O(n) 空间换掉两两比较的 O(n²)
1if target - x in seen: return seen[target - x], i2seen[x] = i3Counter(words).most_common(k)4groups["".join(sorted(w))].append(w)

第 3 章快刷

5 道题:哈希函数、__eq__ 和 __hash__、线性探测、扩容搬了几次,还有 Counter。先自己算出打印什么,再点选项。

猜输出猜错也没关系

同一个多项式哈希,表长 31 和表长 7。打印什么?

1def h(s, m):2    v = 03    for c in s:4        v = (v * 31 + ord(c)) % m5    return v6 7print(h("ab", 31) == h("bb", 31), h("ab", 7) == h("ba", 7))
猜输出猜错也没关系

只写了 __eq__。打印什么?

1class P:2    def __init__(self, x):3        self.x = x4 5    def __eq__(self, other):6        return self.x == other.x7 8a, b = P(1), P(1)9try:10    r = len({a, b})11except TypeError:12    r = "TypeError"13print(a == b, r)
猜输出猜错也没关系

线性探测,表长 7,依次放 3 10 17 4。打印什么?

1m = 72table = [None] * m3for k in [3, 10, 17, 4]:4    i = k % m5    while table[i] is not None:6        i = (i + 1) % m7    table[i] = k8print(table)
猜输出猜错也没关系

拉链法:n 超过桶数就翻倍,搬走全部 n 个。放 20 个以后打印什么?

1m, n, moves = 4, 0, 02for k in range(20):3    n += 14    if n > m:5        moves += n6        m *= 27print(m, moves)
猜输出猜错也没关系

数 mississippi 的字母。打印什么?

1from collections import Counter2 3c = Counter("mississippi")4print(c.most_common(2), c["z"])