[HAI] twoSumHashtable

This commit is contained in:
2024-11-23 04:33:24 +03:00
parent 0cabf5961f
commit 1eddd38b3f
3 changed files with 41 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
export function twoSumHashTable(nums: number[], target: number): number[] {
const result: number[] = [];
const hashTable: Record<string, number> = {};
let i = 0;
while (i < nums.length) {
let key = nums[i];
let val = i;
let searchKey = String(target - key);
if (searchKey in hashTable) {
result.push(hashTable[searchKey]);
result.push(val);
break;
} else {
hashTable[key] = val;
}
i++
}
return result;
};