Algorithm 当使用线性探测构建哈希表以解决冲突时,额外的项是否始终添加到哈希表中,还是仅在发生冲突时才添加?

Algorithm 当使用线性探测构建哈希表以解决冲突时,额外的项是否始终添加到哈希表中,还是仅在发生冲突时才添加?,algorithm,key,hashtable,Algorithm,Key,Hashtable,我正在构建一个表,当发生冲突时,试图在表中插入一个新键的操作遵循序列{hash(x)+I,其中I=1,2,3,…}。如果我使用线性探测构建哈希表,我的Insert()算法是否会执行以下操作: hashValue = hash(x) while hashValue is taken in table hashValue += 1 hashValue = hash(x) + 1 while hashValue is taken in table hashValue += 1 其中,我只在

我正在构建一个表,当发生冲突时,试图在表中插入一个新键的操作遵循序列{hash(x)+I,其中I=1,2,3,…}。如果我使用线性探测构建哈希表,我的Insert()算法是否会执行以下操作:

hashValue = hash(x)
while hashValue is taken in table
  hashValue += 1
hashValue = hash(x) + 1
while hashValue is taken in table
  hashValue += 1
其中,我只在发生冲突时添加增量值,或者我会在I=1时从一开始就将增量值添加到散列中,如下所示:

hashValue = hash(x)
while hashValue is taken in table
  hashValue += 1
hashValue = hash(x) + 1
while hashValue is taken in table
  hashValue += 1

它不会造成伤害(它只是将探测序列移动一个元素),但也没有任何好处,从概念上讲,这有点愚蠢。这就是为什么规范形式从hash(x)开始,只有在遇到冲突时才会递增。

只要你始终如一地这样做,这并不重要。向哈希代码中添加一个(或任何其他常量)的效果对表的组成没有影响,除了桶编号将通过常量“偏移量”进行“偏移”。由于桶编号是has表的私事,因此没有人应该关心

本质上,线性探测哈希函数是

H(x, i) = (H(x) + i) % N

其中
N
是存储桶的数量。通常从零开始
i
,这意味着只有在发生冲突时才增加哈希值。

我想这两种方法都可以,但正式来说,前者才是您想要的:运行哈希函数,然后增加结果。