使用 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 }

更新於:15-Jun-2020

842 次檢視

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.