它使用雜湊函數來計算儲存桶或槽數組的索引,從中可以找到所需的值。
哈希映射的主要優點是它的效率。插入新的鍵值對、刪除鍵值對以及查找給定鍵的值等操作都非常快,通常平均需要恆定時間。
let hashMap = {}; hashMap['key1'] = 'value1'; hashMap['key2'] = 'value2'; console.log(hashMap['key1']); // Outputs: value1
單獨連結:在單獨連結中,哈希表數組中的每個槽都包含一個連結列表(或可以容納多個項目的其他資料結構)。當發生衝突時,新的鍵值對會被加入到鍊錶對應索引的末端。
這是在 JavaScript 中使用單獨連結的雜湊映射的簡單實作:
class HashMap { constructor() { this.table = new Array(100).fill(null).map(() => []); } put(key, value) { const index = this.hash(key); const chain = this.table[index]; const existingPair = chain.find(([existingKey]) => existingKey === key); if (existingPair) { existingPair[1] = value; } else { chain.push([key, value]); } } get(key) { const index = this.hash(key); const chain = this.table[index]; const pair = chain.find(([existingKey]) => existingKey === key); if (pair) { return pair[1]; } return null; } hash(key) { let hash = 0; for (let i = 0; i線性探測:在線性探測中,當發生衝突時,哈希映射會檢查數組中的下一個槽(如果也已滿,則繼續到下一個槽,依此類推) ,直到找到一個空槽,可以儲存新的鍵值對。
這是在 JavaScript 中使用線性探測的雜湊映射的簡單實作:
class HashMap { constructor() { this.table = new Array(100).fill(null); } put(key, value) { let index = this.hash(key); while (this.table[index] !== null) { index = (index 1) % this.table.length; } this.table[index] = [key, value]; } get(key) { let index = this.hash(key); while (this.table[index] !== null) { if (this.table[index][0] === key) { return this.table[index][1]; } index = (index 1) % this.table.length; } return null; } hash(key) { let hash = 0; for (let i = 0; i在這兩個範例中,雜湊方法都是一個簡單的雜湊函數,它將鍵轉換為用作數組中索引的整數。在現實場景中,您可能會使用更複雜的雜湊函數來減少衝突的可能性。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3