目录
正在加载目录…
正在阅读专栏 Algorithms:CLRS + MIT 6.006 第 8 篇 · 共 24 篇 · 33%

Hashing with Chaining:冲突、Load Factor 与 Expected O(1)

发布于 2026-09-18 18:11 · 最后编辑于 2026-09-18 18:11 · 版本 v1 · 字数 5,932 · 预计阅读 12 分钟 👁 17 次阅读

Algorithms:Hashing with Chaining

本文逐段翻译 MIT 6.006 Fall 2011 Lecture 8《Hashing with Chaining》,从 dictionary ADT 和 Python dictionary 出发,说明 direct-access table 的局限,介绍 prehashing、hash function、collision 与 chaining,并分析 simple uniform hashing 下的 expected complexity。

TL;DR

  • Dictionary ADT:维护带 key 的 items,支持 insert、delete 和 search。
  • Direct access:把 key 直接当作 array index 可以做到 O(1),但要求 keys 是 nonnegative integers,且 key universe 不能太大。
  • Hashing:用 h: U → {0, ..., m-1} 把巨大 universe 映射到有限 table slots;不同 keys 映射到同一 slot 就产生 collision。
  • Chaining:每个 slot 保存一个 linked list,把映射到该 slot 的所有 items 串起来;最坏情况为 Θ(n),但在 simple uniform hashing 且 load factor α=n/m=O(1) 时,expected operation time 为 Θ(1+α)=O(1)。
  • Hash function:讲义介绍 division method、multiplication method 和 universal hashing;hash function 的质量直接决定 chain length 与 performance。

目录

章节说明
Lecture 8:Hashing Idictionary ADT 与目标
Python dictionary 与 direct-access table从 dict 到直接寻址
Prehashing 与 hashingkey universe、table size 与映射
Collision 与 chaining冲突处理与操作过程
Simple uniform hashingload factor 与 expected complexity
Hash functionsdivision、multiplication 与 universal hashing
复杂度总结worst-case 与 expected-case
小结本讲要点

Lecture 8:Hashing I

dictionary 是 computer science 中最常见的 data structure 之一。它可以用来表示:

text
English word → definition
username     → account object
IP address   → network interface
port number  → socket / application
variable name → value
virtual address → physical address

本讲的目标是实现一个 dictionary,使每个 operation 的目标复杂度接近 O(1)。上一讲的 balanced BST 可以为每个 operation 提供 O(log n),但 dictionary 不一定需要 ordered operations;如果只需要按照 exact key 查找,hash table 可以更快。

Python dictionary 与 direct-access table

dictionary ADT 维护一个 items set。每个 item 有一个 key,并支持:

text
insert(item)       把 item 加入 set
delete(item)       从 set 中删除 item
search(key)        如果 key 存在,返回对应 item

假设 items 的 keys 互不相同;如果插入相同 key 的新 item,可以将旧 item 覆盖。

Python dictionary 存储 (key, value) pairs:

python
d = {'algorithms': 5, 'cool': 42}

d.items()       # [('algorithms', 5), ('cool', 42)]
d['cool']       # 42
d[42]           # KeyError
'cool' in d     # True
42 in d         # False

Python set 可以看成一种只有 keys、没有 values 的 dictionary。

Direct-access table

最简单的方法是建立一个 array,并把 key 直接作为 index:

text
T[key] = item

如果 key 是 0..m-1 的 nonnegative integer,那么:

text
search(key):直接读取 T[key],O(1)
insert(item):写入 T[key],O(1)
delete(item):清空 T[key],O(1)

但是 direct-access table 有两个问题:

  1. keys 必须是 nonnegative integers;如果 key 是 string、tuple 或一般 object,就不能直接作为 array index。
  2. key range 很大时,table 需要巨大空间,即使实际上只存储了极少数 keys。例如,只有一个 key 等于 2^256,也不应该为了它建立一个拥有 2^256 个位置的 array。

hashing 的目标是保留 random-access 的速度,同时把巨大的 key universe 压缩到合理大小的 table 中。

Prehashing 与 hashing

Prehashing

要处理 arbitrary objects,第一步是把它们转换为 integers,这个过程称为 prehashing。由于 computer 中的 objects 都有 finite representation,理论上可以把 key universe 映射到可数的 integer set。

Python 提供:

python
hash(object)

讲义指出,这个 Python operation 严格说更像“prehash”:它把 number、string、tuple 或实现了 hash protocol 的 object 映射为 integer。对没有自定义实现的 object,默认值可能与 object 的 identity 或 memory address 有关。

理想情况下,希望:

text
x = y  ⇔  hash(x) = hash(y)

实际实现会使用各种 heuristics。一个重要限制是:item 放入 table 后,它的 key 不应发生变化,否则 hash table 可能再也找不到它。由于 list 等 mutable objects 的内容可以变化,它们通常不能直接作为 Python dictionary keys。

Hash function

prehash 只把 arbitrary key 转成 integer;还需要把整个 key universe U 映射到 table 的 m 个 slots:

text
h: U → {0, 1, ..., m - 1}

这里:

text
U:所有可能 keys 的 universe
K:当前 dictionary 中实际出现的 keys
m:table slots 数量
n:当前存储的 keys 数量

理想情况下,m 与 n 同数量级:

text
m ≈ n

这样每个 slot 平均只需要承载常数数量的 keys。

Collision 与 chaining

因为 U 通常远大于 m,不同 keys 映射到同一个 slot 是不可避免的。两个 keys k_i 和 k_j 发生 collision,当且仅当:

text
h(k_i) = h(k_j)

讲义介绍两种 collision handling approaches:

text
chaining:本讲
open addressing:Lecture 10

Chaining 的表示

hash table 的每个 slot 保存一个 linked list:

text
T[0] → item → item → ...
T[1] → item
T[2] → empty
...
T[m-1] → item → item

所有满足 h(key) = i 的 items 都放入 T[i] 对应的 chain。插入时,先计算 hash,再把 item 加入对应 list;删除和 search 也先定位 slot,再在 list 中处理。

Operations

text
CHAINED-SEARCH(T, key):
    i ← h(key)
    在 linked list T[i] 中搜索 key
    找到则返回 item,否则返回 NOT-FOUND

CHAINED-INSERT(T, item):
    i ← h(key(item))
    把 item 插入 linked list T[i]

CHAINED-DELETE(T, item):
    i ← h(key(item))
    从 linked list T[i] 中删除 item

如果 list 的头部插入是 O(1),那么 insert 不需要遍历 chain;search 和 delete 的成本取决于对应 chain 的长度。

Worst case

最坏情况下,所有 n 个 keys 都被 hash 到同一个 slot:

text
T[i] → k₁ → k₂ → ... → kₙ

此时 chain 就退化成一个 linked list,search 和 delete 需要 Θ(n):

text
worst-case operation time = Θ(n)

所以 hashing 的性能依赖于两个因素:hash function 是否把 keys 分散开,以及 table 是否有足够 slots。

Simple uniform hashing

为了分析 expected performance,讲义使用一个明确但有些理想化的 assumption:

每个 key 等概率地被 hash 到任意一个 table slot,并且一个 key 被 hash 到哪里,与其他 keys 被 hash 到哪里相互独立。

这称为 simple uniform hashing。它不是对所有真实 hash functions 都成立的事实,而是用于推导平均 chain length 的数学模型。

令:

text
n = table 中实际存储的 keys 数量
m = table slots 数量
α = n / m = load factor

平均而言,每个 slot 的 chain length 是:

text
expected chain length = n / m = α

一次 search 的 expected cost 包括两部分:

  1. 计算 hash function 并通过 random access 找到对应 slot:Θ(1);
  2. 在 chain 中搜索:expected Θ(α)。

因此:

text
expected search time = Θ(1 + α)

如果令 m = Ω(n),则 α = O(1),从而:

text
expected operation time = O(1)

insert 可以在 chain 头部完成,因此在 hash calculation 为 constant-time 的前提下通常也是 O(1);delete 需要先找到 item,若使用 linked list,仍受 chain length 影响。

Load factor 的含义

text
α < 1:table 比 items 多,chains 较短
α ≈ 1:平均每个 slot 一个 item
α ≫ 1:chains 较长,hash table 逐渐接近 linked-list search

因此实际 hash table 通常会设置 resize threshold,在 load factor 过高时增大 table 并重新 hash items;table doubling 会在下一讲进一步讨论。

Hash functions

simple uniform hashing 给出了理想目标,但实际中需要选择具体的 hash function。讲义讨论三种方法:division method、multiplication method 和 universal hashing。

Division method

最简单的 hash function 是:

text
h(k) = k mod m

它把 integer key 除以 m 后的 remainder 作为 table slot。division method 在 m 是 prime number 时通常比较实用;但 m 不应太接近 2 或 10 的 power,否则如果 keys 的低位 bit 或 decimal digits 存在规律,hash 结果可能只依赖 key 的一小部分:

text
坏例子:m = 2^r,h(k) 可能只观察 k 的低 r 个 bits

division method 的两个实际问题是:

  1. 找到合适的 prime number 不方便;
  2. integer division 通常比 multiplication 和 bit extraction 慢。

Multiplication method

设 machine word 有 w bits,选择一个 multiplier a,并令 table size 为 m = 2^r。multiplication method 可以写成:

text
h(k) = floor(((a · k) mod 2^w) / 2^{w-r})

也就是:

  1. 计算 a·k;
  2. 只保留 product 的低 w bits;
  3. 取其中的高 r bits 作为 hash value。

讲义给出的实践建议包括:a 应为 odd,且大致满足:

text
2^{w-1} < a < 2^w

同时不要让 a 太接近边界。相比 division,multiplication 和 bit extraction 通常更快。

Universal hashing

如果 hash function 固定不变,攻击者或不幸的 input distribution 可能故意构造大量 collisions。universal hashing 的思路是:从一个 hash functions family H 中随机选择 h,让任意两个不同 keys 发生 collision 的概率足够小。

一个常用的 family 是:

text
h(k) = ((a k + b) mod p) mod m

其中:

text
p:大于 key universe |U| 的 large prime
a、b:从 {0, 1, ..., p-1} 中随机选择

对于任意不同的 k₁ 和 k₂,从这个 family 随机选择 a,b 时,有:

text
Pr[h(k₁) = h(k₂)] ≤ 1/m

这意味着,即使 keys 是 worst-case 选择的,只要 hash function 是随机选择的,collision probability 仍然受到控制。讲义没有证明这个 lemma,而是直接使用它分析 expected collisions。

Expected collisions

固定一个 key k₁,对另一个 key k₂ 定义 indicator:

text
X_{k₁,k₂} = 1,如果 h(k₁) = h(k₂)
             0,否则

k₁ 与其他 n-1 个 keys 的 collision 数量是:

text
∑_{k₂} X_{k₁,k₂}

利用 expectation 的 linearity:

text
E[collision count with k₁]
  = ∑_{k₂} E[X_{k₁,k₂}]
  = ∑_{k₂} Pr[h(k₁) = h(k₂)]
  ≤ ∑_{k₂} 1/m
  ≈ n/m
  = α

所以 universal hashing 可以得到和 simple uniform hashing 同样数量级的 expected chain length。它的价值在于:不要求 input keys 本身是 random,只需要 hash function 从合适的 family 中随机选择。

复杂度总结

操作 / 条件Worst caseSimple uniform / universal hashing 的 expected bound
insert,chain 头部插入Θ(1)(不含 resize)Θ(1)
searchΘ(n)Θ(1 + α)
deleteΘ(n)Θ(1 + α)
hash table 的 spaceΘ(m+n)Θ(m+n)
当 m = Ω(n)Θ(n) worst case 仍可能出现O(1) expected operation

这里的 O(1) expected 并不是无条件保证:它依赖 hash function 的分布性质、constant-time prehash/hash calculation,以及 load factor 不持续增长。若 table 需要扩容,还要额外分析 resize 的 amortized cost。

还应区分 hash table 与 balanced BST 的能力:

需求Hash tableBalanced BST
exact-key searchexpected O(1)O(log n)
insert / deleteexpected O(1)O(log n)
predecessor / successor不自然,通常需要额外结构O(log n)
ordered traversal不提供直接支持 inorder traversal
worst-case guarantee普通 chaining 可能 Θ(n)AVL / red-black 可维持 O(log n)

因此 data structure 的选择应由 ADT interface 决定:dictionary 只需 exact lookup 时 hash table 很合适;如果需要 ordering,就应考虑 balanced BST 或其他 ordered structure。

小结

dictionary 的 direct-access table 可以用 O(1) array indexing,但要求 key 是 small integer。prehashing 先把 arbitrary object 转为 integer,hashing 再用 h: U → {0,...,m-1} 把巨大 universe 映射到有限 table。

collision 无法避免;chaining 将同一 slot 的 items 放进 linked list。最坏情况下所有 keys 落在一个 slot,operation 退化为 Θ(n);在 simple uniform hashing 或 universal hashing 的假设下,平均 chain length 是 load factor α=n/m,search 与 delete 的 expected cost 为 Θ(1+α)。当 m=Ω(n) 时,exact-key dictionary operation 达到 expected O(1)。

参考资料

← 返回列表
← 上一篇 Counting Sort、Radix Sort 与 Sorting Lower Bounds 下一篇 → Table Doubling、Amortized Analysis 与 Karp-Rabin

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论