Robin Hood哈希实战:走得更远的键抢先落位,删除后为何还要搬动邻居

10-07 7阅读

开放寻址哈希表把冲突键继续放进后续槽位。Robin Hood规则在遇到冲突时比较两项离各自起始槽有多远,让走得更远的一项留下,另一项继续探测。这个局部交换规则影响插入,也给查找提前停止提供依据。

本文做一个固定容量的整数键值表,保存键、值和探测距离,至少留一个空槽。为了让冲突看得清楚,起始槽直接用键对容量取余;它是机制实验,不是替换Python字典的生产哈希函数。

Robin Hood哈希实战:走得更远的键抢先落位,删除后为何还要搬动邻居

AI模型生成的概念插图:弧形槽位与不同长短的到达路径表达探测距离参与落位决策;不表示正文准确交换轨迹,非真实哈希表界面或实测截图。

完整程序与实际输出

保存以下完整程序为demo.py,执行python3 demo.py。本次在Linux、CPython 3.12.14实际运行,退出码为0,标准错误为空。只使用标准库和固定内存数据,不安装软件,也不访问网络或业务文件。

from random import Random


class RobinHoodMap:
    def __init__(self, capacity=8):
        if type(capacity) is not int or not 2 <= capacity <= 128:
            raise ValueError("capacity must be from 2 to 128")
        self.slots = [None] * capacity
        self.count = 0

    def _check(self, key):
        if type(key) is not int:
            raise ValueError("integer key required")

    def _locate(self, key):
        self._check(key)
        size = len(self.slots)
        index, distance = key % size, 0
        for _ in range(size):
            item = self.slots[index]
            if item is None or item[2] < distance:
                return None
            if item[0] == key:
                return index
            index = (index + 1) % size
            distance += 1
        return None

    def get(self, key):
        index = self._locate(key)
        if index is None:
            raise KeyError(key)
        return self.slots[index][1]

    def put(self, key, value):
        self._check(key)
        if type(value) is not int:
            raise ValueError("integer value required")
        existing = self._locate(key)
        if existing is not None:
            self.slots[existing] = (key, value, self.slots[existing][2])
            return
        size = len(self.slots)
        if self.count >= size - 1:
            raise OverflowError("one empty slot must remain")
        index, distance = key % size, 0
        while self.slots[index] is not None:
            resident = self.slots[index]
            if resident[2] < distance:
                self.slots[index] = (key, value, distance)
                key, value, distance = resident
            index = (index + 1) % size
            distance += 1
        self.slots[index] = (key, value, distance)
        self.count += 1

    def remove(self, key):
        hole = self._locate(key)
        if hole is None:
            raise KeyError(key)
        value = self.slots[hole][1]
        size = len(self.slots)
        following = (hole + 1) % size
        while self.slots[following] is not None and self.slots[following][2] > 0:
            k, v, distance = self.slots[following]
            self.slots[hole] = (k, v, distance - 1)
            hole = following
            following = (following + 1) % size
        self.slots[hole] = None
        self.count -= 1
        return value


def layout(table):
    return [None if item is None else (item[0], item[2]) for item in table.slots]


table = RobinHoodMap()
for key in (0, 8, 1, 16):
    table.put(key, key * 10)
print("key/distance before delete:", layout(table))
assert table.remove(8) == 80
print("after deleting 8:", layout(table))
table.put(16, 999)
assert table.get(16) == 999 and table.count == 3
print("updated key 16:", table.get(16), "count:", table.count)
wrapped = RobinHoodMap()
for key in (7, 15, 23):
    wrapped.put(key, key)
wrapped.remove(7)
assert wrapped.get(15) == 15 and wrapped.get(23) == 23
print("wrapped cluster:", layout(wrapped))
rng, checks = Random(61), 0
for _ in range(30):
    trial, reference = RobinHoodMap(), {}
    for step in range(100):
        key = rng.randrange(-8, 24)
        if rng.randrange(2):
            if key in reference or len(reference) < 7:
                trial.put(key, step)
                reference[key] = step
            else:
                before = list(trial.slots)
                try:
                    trial.put(key, step)
                except OverflowError:
                    pass
                else:
                    raise AssertionError("capacity limit ignored")
                assert trial.slots == before
        elif key in reference:
            assert trial.remove(key) == reference.pop(key)
        else:
            try:
                trial.remove(key)
            except KeyError:
                pass
            else:
                raise AssertionError("missing key removed")
        for candidate in range(-8, 24):
            try:
                actual = trial.get(candidate)
            except KeyError:
                assert candidate not in reference
            else:
                assert actual == reference[candidate]
            checks += 1
        assert trial.count == len(reference)
        for index, item in enumerate(trial.slots):
            if item is not None:
                assert item[2] == (index - item[0] % 8) % 8
print("dictionary comparison checks:", checks)
print("wraparound, updates, deletion, capacity: passed")

以下为上述程序的实际标准输出,独立于源码列出:

key/distance before delete: [(0, 0), (8, 1), (16, 2), (1, 2), None, None, None, None]
after deleting 8: [(0, 0), (16, 1), (1, 1), None, None, None, None, None]
updated key 16: 999 count: 3
wrapped cluster: [(23, 1), None, None, None, None, None, None, (15, 0)]
dictionary comparison checks: 96000
wraparound, updates, deletion, capacity: passed

探测距离从自己的起始槽计算

容量为八时,键零、八、十六的起始槽都为零。若键八最后放到槽一,它的距离为一;键一放到槽三,距离则为二。距离只说明这条记录相对自身起点走过几格,不是键的大小或插入时间。

槽位是环形的,到末尾以后回到零。因此距离可核对为“当前槽减起始槽,再对容量取余”。负整数键也合法,Python的正模数取余会把起始槽放回零到容量减一的范围。

插入时交换的是整条待安置记录

新键从距离零开始探测。如果槽里住着距离更短的条目,新键占据这个槽,旧条目成为接下来要安置的对象。继续走到下一格时,必须从被挤出条目原来的距离加一,不能沿用新键之前的距离。

代码先把新条目的三元组写入槽,再接住resident中的键、值、距离。距离相等时不交换,直接继续走。到空槽才完成整次插入,count只增加一次,不能每发生一次中间交换就把总条目数加一。

四个键展示一次真正的抢位

按零、八、一、十六的次序插入。前三项落在槽零、一、二,距离分别为零、一、一。十六走到槽二时已经离起始槽两步,而原住户键一只走了一步,于是十六抢到槽二,键一移到槽三。

输出中的非空条目因此为(0,0)、(8,1)、(16,2)、(1,2),每对数字代表键和距离。这个例子也表明,不能根据槽位先后来判断键的数值顺序;哈希表并未完成排序。

查找遇到更短距离时,可以判定不存在

查询从目标键自己的起始槽开始,逐格增加查询距离。遇到空槽即可停止;如果当前住户的距离严格小于查询距离,也可判定目标不在后面。目标若曾走到这里,插入规则本应让更远的目标抢下这个位置,而不会让它继续越过较近的住户。

这一早停性质由插入规则和配套删除操作共同维持。它并不要求整个连续占用段的距离全局递增,不同起点的条目接到同一段时,距离可以下降。把早停规则解释成“数组按距离排好序”会得到错误的不变式。

更新旧键时先用同一查找过程确定位置,只替换值并保留距离,不再重新插入一份。因此容量已达到本例上限时,更新仍然允许;只有不存在的新键才会在任何交换前收到OverflowError。

删除留下的洞,要让后续探测链继续可达

若只把槽一的键八设为空,查找后面的十六会在空槽提前停下。remove因此把下一格中距离大于零的条目往洞里搬一格,同时将它的距离减一,洞也随之向后移动。直到遇见空槽或距离为零的条目,才把最终的洞清空。

距离为零表示该条目就在自己的起始槽,没有理由跨过起点向前搬。保持它原位,配合Robin Hood的查找不变量,便能结束当前修补。删除八后,十六移动到槽一、键一移动到槽二,它们的距离都变为一。

同样的逻辑必须跨过数组末端。程序把七、十五、二十三连成跨越槽七、零、一的探测链,删除七后,十五回到槽七、二十三回到槽零。普通的线性切片搬移若忘记环绕,便会破坏这个例子。

固定容量版本不承诺恒定最坏时间

本例没有扩容或墓碑,最多使用容量减一个槽。容量检查发生在新键插入前,因此拒绝不会留下交换到一半的表。查询不存在的键和删除不存在的键抛出KeyError,不能把某个合法整数值当作缺失哨兵。

在很差的哈希分布下,一次查找、插入或删除仍可能扫描容量级别的槽位,最坏时间O(capacity),存储O(capacity)。Robin Hood有降低探测差异的研究结论,但不能把特定分布的平均表现搬来替本例这个简单取余函数承诺常数时间。

真实实现还需考虑负载因子、扩容时重新计算起始槽、键相等关系、迭代器失效以及并发修改。任何一项改变都要保持查找、插入和删除使用同一套槽位规则。

对照字典,还要核验每个距离字段

测试固定随机种子,生成三十组、每组一百步插入更新和删除,在每步后查询负八到二十三的全部键,共96000次与Python字典比较。出现容量拒绝时,另外保存槽数组确认完全未变。

程序还逐槽重算实际位移,检查保存的距离等于环形位置差,并核对count等于独立字典大小。返回值正确但距离记错可能暂时不暴露,随后一次查找早停或删除才会出错,因此元数据检查同样必要。

参考资料

一手资料与本地运行核查日期:2026年10月6日。代码和算例为本文独立编写,测试只验证给定输入与性质,不代表真实业务性能。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。