【发布时间】:2021-12-22 22:20:46
【问题描述】:
我正在尝试在 JavaScript 中实现 hashmap 功能,并希望将所有内容保持在恒定时间内。
问题1:在恒定时间内从数组中删除元素(O(1))我正在使用数组。
问题 2: 解决冲突问题的最佳方法,以防我们为不同的键使用相同的哈希值。
问题 3: 创建哈希码的最佳方式。目前我正在使用每个字符的一些 ASCII 值。
代码示例
class myHashMap {
constructor(size = 0 ){
if(size){
this.hashMap = new Array(size).fill(null);
this.size = size;
}
else{
this.hashMap = new Array();
this.size = 0;
}
}
hash(key){
// Here hashing can have collision
//for example: 122 and 212 will have same hash which is not correct
let CharArray = key.split("");
return CharArray.reduce((acc,current) => {
return acc+current.charCodeAt(0);
},0);
}
set(key,value)
{
this.size++;
this.hashMap[this.hash(key)] = value;
}
get(key){
return this.hashMap[key];
}
has(key){
return this.hashMap[key];
}
remove(key)
{
this.size--;
this.hashMap.splice(this.hash(key),1);
// Here I need to remove element in O(1)
}
}
【问题讨论】:
-
向我们展示您迄今为止尝试过的内容,并提供一个最小可重复的示例stackoverflow.com/help/minimal-reproducible-example
-
@wooooooo 我用代码示例更新了问题
-
只需使用
this.hashMap[this.hash(key)] = null;!不要做任何拼接,这会修改数组的大小并将所有元素移动到索引之后(O(n))。 -
"问题 2:解决冲突问题的最佳方法"、"问题 3:创建哈希码的最佳方法" - 请保留为一个每个问题的问题。请注意,维基百科在 resolving hash collisions 和 choosing good hash functions 上有完整的文章
-
@Faisal "我还需要计算 O(1) 中的哈希值。" - 不,你不需要。或者,您已经这样做了 -
O(n)中的n指的是哈希表的大小,而不是键的大小。
标签: javascript arrays performance hashmap time-complexity