使用 JavaScript 向哈希表中添加元素
在向哈希表中添加元素时,最重要的部分是解决冲突。我们将使用链接来解决相同的问题。这里有一些你可以了解的其他算法:https://en.wikipedia.org/wiki/Hash_table#Collision_resolution
现在让我们来看看实现。我们将创建一个哈希函数,该函数仅处理整数以保持简单。但是更复杂的算法可用于对每个对象进行哈希 −
示例
put(key, value) {
let hashCode = hash(key);
for(let i = 0; i < this.container[hashCode].length; i ++) {
// Replace the existing value with the given key
// if it already exists
if(this.container[hashCode][i].key === key) {
this.container[hashCode][i].value = value; return;
}
}
// Push the pair at the end of the array
this.container[hashCode].push(new this.KVPair(key, value));
}你可以使用以下方法测试它:
示例
let ht = new HashTable(); ht.put(10, 94); ht.put(20, 72); ht.put(30, 1); ht.put(21, 6); ht.put(15, 21); ht.put(32, 34); ht.display();
输出
这将给出以下输出 −
0:
1:
2:
3:
4: { 15: 21 }
5:
6:
7:
8: { 30: 1 }
9: { 20: 72 }
10: { 10: 94 } -->{ 21: 6 } -->{ 32: 34 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP