使用 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-6-2020

842 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.