[HAI] twoSumHashtable etalon by Max
parent
7b7e228ba3
commit
78b50806e3
@ -1,24 +1,38 @@
|
|||||||
export function twoSumHashTable(nums: number[], target: number): number[] {
|
// export function twoSumHashTable(nums: number[], target: number): number[] {
|
||||||
const result: number[] = [];
|
// const result: number[] = [];
|
||||||
const hashTable: Record<string, number> = {};
|
// const hashTable: Record<string, number> = {};
|
||||||
let i = 0;
|
// let i = 0;
|
||||||
|
|
||||||
|
|
||||||
while (i < nums.length) {
|
// while (i < nums.length) {
|
||||||
let key = nums[i];
|
// let key = nums[i];
|
||||||
let val = i;
|
// let val = i;
|
||||||
let searchKey = String(target - key);
|
// let searchKey = String(target - key);
|
||||||
|
|
||||||
if (searchKey in hashTable) {
|
// if (searchKey in hashTable) {
|
||||||
result.push(hashTable[searchKey]);
|
// result.push(hashTable[searchKey]);
|
||||||
result.push(val);
|
// result.push(val);
|
||||||
break;
|
// break;
|
||||||
} else {
|
// } else {
|
||||||
hashTable[key] = val;
|
// hashTable[key] = val;
|
||||||
}
|
// }
|
||||||
|
|
||||||
i++
|
// i++
|
||||||
}
|
// }
|
||||||
|
|
||||||
|
// return result;
|
||||||
|
// };
|
||||||
|
|
||||||
return result;
|
export function twoSumHashTable(nums: number[], target: number): number[] {
|
||||||
|
let usedNums = {};
|
||||||
|
|
||||||
|
for (let idx = 0; idx < nums.length; idx++) {
|
||||||
|
let secondNum = nums[idx];
|
||||||
|
let firstNum = target - secondNum;
|
||||||
|
if (firstNum in usedNums) {
|
||||||
|
return [usedNums[firstNum], idx];
|
||||||
|
}
|
||||||
|
usedNums[secondNum] = idx;
|
||||||
|
}
|
||||||
|
return [];
|
||||||
};
|
};
|
||||||
|
|||||||
Loading…
Reference in New Issue