今天做题时发现leetcode没给出Js的哈希表实现,无奈只能用c# hashSet做。顺带研究一下Js的实现方式。
上图比较直观,数组+链表 === 哈希表 🤔
class Hashmap {
constructor() {
this._storage = [];
}
// 哈希散列函数 可以换成任意一种 例如MD5
hashStr(str) {
let finalHash = 0;
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
finalHash += charCode;
}
return finalHash;
}
set(key, val) {
let idx = this.hashStr(key);
if (!this._storage[idx]) {
this._storage[idx] = [];
}
this._storage[idx].push([key, val]);
}
get(key) {
let idx = this.hashStr(key);
if (!this._storage[idx]) {
return undefined;
}
for (let keyVal of this._storage[idx]) {
if (keyVal[0] === key) {
return keyVal[1];
}
}
}
}
后来又想起来一件事,自己写后端逻辑时候,直接就是字典结构处理。这不是和HashSet一样吗。。上网查了查:
哈希表与字典的区别
字典元素的顺序就是插入的顺序,而哈希表则不一定。
字典是强类型的,哈希表是弱类型的。