[HAI] twoSumHashtable etalon by Max

This commit is contained in:
2024-11-28 00:36:02 +03:00
parent 7b7e228ba3
commit 78b50806e3
+33 -19
View File
@@ -1,24 +1,38 @@
// 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;
// };
export function twoSumHashTable(nums: number[], target: number): number[] { export function twoSumHashTable(nums: number[], target: number): number[] {
const result: number[] = []; let usedNums = {};
const hashTable: Record<string, number> = {};
let i = 0;
for (let idx = 0; idx < nums.length; idx++) {
while (i < nums.length) { let secondNum = nums[idx];
let key = nums[i]; let firstNum = target - secondNum;
let val = i; if (firstNum in usedNums) {
let searchKey = String(target - key); return [usedNums[firstNum], idx];
if (searchKey in hashTable) {
result.push(hashTable[searchKey]);
result.push(val);
break;
} else {
hashTable[key] = val;
} }
usedNums[secondNum] = idx;
i++
} }
return [];
return result;
}; };