【发布时间】:2015-11-24 19:26:03
【问题描述】:
下面是我使用“桶”进行冲突检测的哈希表实现。我试图确保我能够完全理解哈希表背后的逻辑并将其可视化。这就是我的哈希表的样子:
[[[]
元组中的键值对根据散列函数的输出放置在桶中,即,桶索引。一旦您位于散列存储桶索引处,您就可以将键值对放在存储桶内。如果有任何内容与该确切密钥匹配(一旦在存储桶内),它将在我的实现中被覆盖。当您找到与以前相同的键时会发生碰撞检测,并覆盖其值。
我可以做一些不同的事情吗?也许将具有不同值的键添加到元组的末尾(而不是覆盖值)或者键必须始终是唯一的?是否存在只需要唯一值的情况?
var makeHashTable = function() {
var max = 4;
return {
_storage: [],
retrieve: function(key) {
//when we retrieve, we want to access the bucket in the same way as insert, but we don't need to set it to storage since that is already taken
//care of in the insert function. if there's nothing in the bucket, the loop won't run.
//this function will return null by default.
var bucketIndex = hashFn(key, max);
var bucket = this._storage[bucketIndex];
for (var i = 0; i < bucket.length; i++) {
var tuple = bucket[i];
if (tuple[0] === key) {
return tuple[1];
};
};
return null;
},
insert: function(key, value) {
//hash function gives you the right index
var bucketIndex = hashFn(key, max)
//where you need to put the bucket. if there's no bucket, initialize it.
var bucket = this._storage[bucketIndex] || [];
//now you need to actually store the bucket there.
this._storage[bucketIndex] = bucket;
//implement a collission detection scheme whereby you overwrite the respective value if the key matches, otherwise, add it to the end.
// the for loop won't execute if there is nothing in the bucket if so, jump to line 45 instead
// here is what's happening. If the key doesn't already exist, the key value pair gets added to the end of the bucket.
// if the key matches, IT MUST BE THE SAME VALUE that the hashed key associated with that value previously, so, overwrite it.
for (var i = 0; i < bucket.length; i++) {
var tuple = bucket[i];
if (tuple[0] === key) {
tuple[1] = value;
return;
};
};
bucket.push([key, value]);
}
};
};
HashTable.prototype.remove = function(key) {
var bucketIndex = hashFn(key, max);
var bucket = this._storage[bucketIndex];
for (var i = 0; i < bucket.length; i++) {
var tuple = bucket[i];
if (tuple[0] === k) {
bucket.splice(i, 1);
};
};
};
//don't worry about this generic hashing function please, not the point of my question
var hashFn = function(str, max) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
var letter = str[i];
hash = (hash << 5) + letter.charCodeAt(0);
hash = (hash & hash) % max;
}
return hash;
};
【问题讨论】:
-
与您的问题相切,但 FWIW 最新(全新)版本的 JavaScript 内置了
Map:developer.mozilla.org/en/docs/Web/JavaScript/Reference/… 以上看起来主要是学习的东西,所以它可能不是相关的,但如果是这样的话,我应该提到它。有用于 ES6 之前的浏览器的 shims(现在是大多数浏览器)。
标签: javascript algorithm data-structures hash