两个不同的键可能会哈希到同一个桶 — 冲突。哈希表通过解决冲突和在桶变得拥挤之前进行调整大小来保持平均 O(1),由负载因子控制。
冲突解决
text
Separate chaining: each bucket holds a list
[3] -> ("cat",9) -> ("rat",2) # both hashed to 3
Open addressing: probe to the next free slot
hash=3 taken -> try 4 -> try 5 ... (linear probing)
负载因子和调整大小
text
load factor α = number_of_entries / number_of_buckets
α rises -> more collisions -> slower lookups
When α exceeds a threshold (e.g. 0.75):
-> allocate a bigger array (usually 2x)
-> REHASH every existing key into new buckets
