如何用链式实现哈希表?
这可能是一个愚蠢的问题,但是,看在上帝的份上,我无法弄清楚我在带有链接的哈希表背后的理论中缺少什么。
这就是我的理解:
哈希表使用哈希将键与存储值的位置相关联。有时,散列会为不同的键产生相同的位置,即可能会发生冲突。
在这种情况下,我们可以通过将具有相同位置的所有值存储到该位置的链表来实现链接。
我不明白的是:
当您输入一个键并且哈希函数生成一个存在链接的位置时,它如何确定该位置的链表中的哪个值属于该特定键,而不是另一个值碰撞中涉及钥匙?
我意识到这是基本理论,但如果有人能指出我推理中的错误或告诉我我错过了什么,我将非常感激。
This is probably a stupid question but, I cant for the love of god figure out what I'm missing here in the theory behind hash tables with chaining.
This is what I understand:
A hash table uses a hash to associate a key to a location where a value is stored. Sometimes a hash will produce the same location for different keys, ie collisions may occur.
In this case we can implement chaining by storing all values with the same location to a linked list at that location.
What I don't understand is this:
When you enter a key and the hash function produces a location at which there is chaining, how does it determine which value in the linked list at that location belongs to that specific key, as opposed to another key involved in the collision?
I realize this is basic theory, but if anyone could point out errors in my reasoning or tell me what I'm missing I would very much appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单的方法:维护一个“哈希表条目”的链表,这些条目是键/值对。到达存储桶后,根据存储桶中的所有键检查您的查询键。
Simple way: maintain a linked list of "hash table entries", which are key/value pairs. Once you get to the bucket, check your query key against all keys in the bucket.
您只需通过键对存储桶进行线性搜索即可。
您可能会欣赏以下用 F# 编写的迷你哈希表实现,摘自 此博客post:
此
hashtbl
函数采用键值对的关联序列xs
,构建一个表示为spine
数组的哈希表ResizeArray
存储桶并返回一个 lambda 函数,该函数查找适当的存储桶并在其中针对给定键k
进行线性搜索。线性搜索是使用Seq.pick
函数执行的。You just resort to linear search of the bucket by key.
You may appreciate the following mini hash table implementation written in F#, taken from this blog post:
This
hashtbl
function takes an association sequencexs
of key-value pairs, builds a hash table represented as aspine
array ofResizeArray
buckets and returns a lambda function that finds the appropriate bucket and does a linear search in it for the given keyk
. The linear search is performed using theSeq.pick
function.