Files
hello-algo/ja/codes/javascript/chapter_searching/hashing_search.js
T
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

46 lines
1.6 KiB
JavaScript

/**
* File: hashing_search.js
* Created Time: 2022-12-29
* Author: Zhuo Qinyue ([email protected])
*/
const { arrToLinkedList } = require('../modules/ListNode');
/* ハッシュ探索(配列) */
function hashingSearchArray(map, target) {
// ハッシュテーブルの key:目的の要素、value:インデックス
// ハッシュテーブルにこの key が存在しない場合、-1 を返す
return map.has(target) ? map.get(target) : -1;
}
/* ハッシュ探索(連結リスト) */
function hashingSearchLinkedList(map, target) {
// ハッシュテーブルの key:目的のノードの値、value:ノードオブジェクト
// ハッシュテーブルにこの key が存在しない場合、null を返す
return map.has(target) ? map.get(target) : null;
}
/* 実行用コード */
const target = 3;
/* ハッシュ探索(配列) */
const nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
// ハッシュテーブルを初期化する
const map = new Map();
for (let i = 0; i < nums.length; i++) {
map.set(nums[i], i); // key:要素、value:インデックス
}
const index = hashingSearchArray(map, target);
console.log('目的の要素 3 のインデックス = ' + index);
/* ハッシュ探索(連結リスト) */
let head = arrToLinkedList(nums);
// ハッシュテーブルを初期化する
const map1 = new Map();
while (head != null) {
map1.set(head.val, head); // key:ノードの値、value:ノード
head = head.next;
}
const node = hashingSearchLinkedList(map1, target);
console.log('目的のノードの値 3 に対応するノードオブジェクトは', node);