「这是我参与2022首次更文挑战的第25天,活动详情查看:2022首次更文挑战」
不使用任何内建的哈希表库设计一个哈希映射(HashMap)。
实现 MyHashMap 类:
MyHashMap()用空映射初始化对象- void put(int key, int value) 向 HashMap 插入一个键值对 (key, value) 。如果 key 已经存在于映射中,则更新其对应的值 value 。
int get(int key)返回特定的key所映射的value;如果映射中不包含key的映射,返回-1。
示例:
输入:
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
输出:
[null, null, null, 1, -1, null, 1, null, -1]
解释:
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // myHashMap 现在为 [[1,1]]
myHashMap.put(2, 2); // myHashMap 现在为 [[1,1], [2,2]]
myHashMap.get(1); // 返回 1 ,myHashMap 现在为 [[1,1], [2,2]]
myHashMap.get(3); // 返回 -1(未找到),myHashMap 现在为 [[1,1], [2,2]]
myHashMap.put(2, 1); // myHashMap 现在为 [[1,1], [2,1]](更新已有的值)
myHashMap.get(2); // 返回 1 ,myHashMap 现在为 [[1,1], [2,1]]
myHashMap.remove(2); // 删除键为 2 的数据,myHashMap 现在为 [[1,1]]
myHashMap.get(2); // 返回 -1(未找到),myHashMap 现在为 [[1,1]]
今天的题目让我们设计哈希表(HashMap)。HashMap 是指能 O(1) 时间内进行插入和删除 key-value 对,可以保存不重复元素的一种数据结构。
HashMap 和 HashSet 的区别是 HashMap 保存的每个元素 key-value 对,而 HashSet 保存的是某个元素 key 是否出现过。所以我们把 HashSet 稍作改进即可。
HashMap 是在 时间和空间 上做权衡的经典例子:如果不考虑空间,我们可以直接设计一个超大的数组,使每个key 都有单独的位置,则不存在冲突;如果不考虑时间,我们可以直接用一个无序的数组保存输入,每次查找的时候遍历一次数组。
为了时间和空间上的平衡,HashMap 基于数组实现,并通过 hash 方法求键 key 在数组中的位置,当 hash 后的位置存在冲突的时候,再解决冲突。
设计 hash 函数需要考虑两个问题:
- 通过 hash 方法把键 key 转成数组的索引:设计合适的 hash 函数,一般都是对分桶数取模
%。 - 处理碰撞冲突问题:拉链法 和 线性探测法。
超大数组
因为对于 HashMap 来说,每个元素都需要保存 key:value ,因此,我们把数组的元素设计成 int 型,代表的是 value 。以元素作为索引从数组中获取对应位置保存的数字,就是 value。
- 优点:查找和删除的性能非常快,只用访问 1 次数组;
- 缺点:使用了非常大的空间,当元素范围很大时,无法使用该方法;当存储的元素个数较少时,性价比极低;需要预知数据的取值范围。
var MyHashMap = function() {
this.BASE = 769;
this.data = new Array(this.BASE).fill(0).map(() => new Array());
};
MyHashMap.prototype.put = function(key, value) {
const h = this.hash(key);
for (const it of this.data[h]) {
if (it[0] === key) {
it[1] = value;
return;
}
}
this.data[h].push([key, value]);
};
MyHashMap.prototype.get = function(key) {
const h = this.hash(key);
for (const it of this.data[h]) {
if (it[0] === key) {
return it[1];
}
}
return -1;
};
MyHashMap.prototype.remove = function(key) {
const h = this.hash(key);
for (const it of this.data[h]) {
if (it[0] === key) {
const idx = this.data[h].indexOf(it);
this.data[h].splice(idx, 1);
return;
}
}
};
MyHashMap.prototype.hash = function(key) {
return key % this.BASE;
}