hashmap数据结构在java中的实现



我正在进行一次技术测试,下面给出了问题陈述,我不知道我到底要做什么,请提供一些示例代码来帮助我。

Implement a hash-map data structure from scratch , where both key and value are of string data type.
The details of how a hash works can be found in Chapter 11 of the book "Introduction to
Algorithms" by Cormen, Leiserson, Rivest. You should also refer to Section 3.7 of "The
Algorithm Design Manual" by Steven Skiena. For the required hash-map implementation,
the following conditions hold true:
1. The key is made up of lower-case english alphabets only (a,b,c...z). It can be of any
length.
2. Values are of string data type.
3. The hash function to be used is the one given in Section 3.7 of Skiena.
4. Choose a suitable size of the hash-map, that is, the number of buckets. It should be
greater than 100.
4. Collisions will be resolved using Chaining. Doubly linked lists will be used to store
colliding entries.
You will have to implement the following operations on the hash-map:
a. Create an empty hash-map.
b. Insert a (key, value) pair into the hash-map.
c. Delete a (key) from the hash-map (if present).
d. Search for a (key) in the hash-map, and if present return its value. Else return null.
Thanks in advance.

我相信用英语解释HashMaps会更有帮助。

什么是HashMap

HashMap是一种能够将某些键映射到某些值的数据结构。键和值可以是任何东西。例如,如果我正在制作一个游戏,我可能会将每个用户名链接到一个朋友列表,由字符串列表表示。

为什么要使用HashMap

HashMaps在检索数据方面比数组和链表快得多。经过排序的数组可以通过二进制搜索在O(logn)中找到特定的值。但是,HashMap可以检查它是否包含O(1)中的特定键。所有密钥都必须是唯一的。

HashMaps是如何工作的

HashMaps在后台使用一个数组。数组中的每个元素都是另一个数据结构(通常是链表或二进制搜索树)。HashMap在键上使用一个函数来确定在数组中放置键值的位置。例如,如果我的HashMap接受Strings。。。可能的散列函数可以是:

A. Return the ASCII value of the first letter.
B. Return the sum of the ASCII values of every character in the String.
C. Return the ASCII value of the last character in the String.

返回的值将确定该值进入数组的索引。

但是等等!有个问题

返回的值可能在数组的边界之外。因此,我们应该通过数组长度来对返回值进行mod。

return Math.abs(number%hashMapArray.length);

碰撞:

难道多个键不可能使哈希函数生成相同的索引吗?对例如,如果我们在字符串的哈希映射中使用上面显示的第一个哈希函数。。。任何两个以相同字母开头的字符串都将被赋予相同的数组索引。

这被称为碰撞。

我们如何处理碰撞?

一种碰撞处理技术称为Chaining。由于数组中的每个元素都是链表(或类似的数据结构),因此具有相同哈希值的多个键将被放置在同一链表或"bucket"中。然后,哈希映射能够通过使用哈希函数计算哈希代码并搜索特定的链表来检索值,以查看它是否包含具有相同关键字的值。

必须编写一个好的散列函数以避免冲突。

链接的优势:

-数组不能溢出

-数据可以很容易地删除

链接的缺点:

-如果bucket包含很长的链表,则可能会影响性能。

条目的总数与存储桶的数量之比称为负载系数。如果负载系数过低,就会浪费大量空间。如果负载因子太高,散列的优势就会丧失。负载系数的一个很好的折衷方案是.75

最新更新