哈希表和处理冲突
假设哈希表表示为大小为 7 的数组。我们要存储由三位数字组成的字符串。主哈希密钥是第二个数字模 7 的数值。辅助哈希密钥是第三个数字模 4 的数值加 1。将以下字符串插入最初为空的哈希表中:“111”、“222”、“737”、“323”和“234”。
我的回复:
- 0 - 234
- 1 - 111
- 2 - 222
- 3 - 737
- 4 - 323
- 5 -
6 -
111; 1 mod 7 = 1
- 222; 2 模 7 = 2
- 737; 3 模 7 = 3
- 323; 3 模 4 + 1 = 4
- 234; 4 mod 4 + 1 = 4 (0)
这是正确的吗?
Assume a hashtable is represented as an array of size 7. We want to store strings consisting of three digits. The primary hash key is the numerical value of the second digit modulo 7. The secondary hash key is the numerical value of the third digit modulo 4 increased by one. Insert the following strings into the initially empty hashtable: "111", "222", "737", "323" and "234".
My response:
- 0 - 234
- 1 - 111
- 2 - 222
- 3 - 737
- 4 - 323
- 5 -
6 -
111; 1 mod 7 = 1
- 222; 2 mod 7 = 2
- 737; 3 mod 7 = 3
- 323; 3 mod 4 + 1 = 4
- 234; 4 mod 4 + 1 = 4 (0)
is that correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想提及您正在使用什么类型的哈希。根据您的描述,我认为它是 cuckoo 哈希。如果是这种情况,直到最后一次插入为止都没有问题。在插入 234 之前,您有:
尝试使用
h1
插入 234 会得到3 mod 7 = 3
的密钥,但 3 已经包含 373。继续讨论h2
我们得到4 mod 4 + 1 = 1
,但是1已经包含111。此时没有更多的哈希函数,所以我们在1处插入234,重新哈希 111。用
h1
哈希 111 再次得到 1,h2
得到1 mod 4 + 1 = 2
,但是 2 已经包含 222,所以我们将 111 存储在 2 处并重新散列 222 等。在这种情况下,最终您会发现所有键都适合。在它们的条目不全部适合的情况下(即重新插入进入无限循环),需要调整表的大小并使用新的哈希函数重新哈希。You might want to mention what type of hash you are using. I assume from your description that it is cuckoo hashing. If this is the case you are fine up until the last insertion. Before 234 is inserted you have:
Trying to insert 234 with
h1
gives a key of3 mod 7 = 3
, but 3 already contains 373. Moving on toh2
we get4 mod 4 + 1 = 1
but 1 already contains 111. At this point there are no more hash functions, so we insert 234 at 1 and rehash 111.Hashing 111 with
h1
gives 1 again,h2
gives1 mod 4 + 1 = 2
, but 2 already contains 222, so we store 111 at 2 and rehash 222, etc. In this case, eventually you will find all the keys fit. In the case where they entries don't all fit (i.e. the reinsertion enters an infinite cycle) the table needs to be resized and rehashed with new hash functions.我不确定如果检查辅助哈希键后仍然存在冲突,这个问题希望您做什么,但我认为它是这样的:
如果在第二次碰撞后前进 1,结果将为
I'm not sure what this problem wants you to do if there is still a collision after the secondary hash key is checked, but I think it goes like this:
If you advance by one after the second collision, the result would be