[HAI] twoSumHashtable etalon by Max
parent
7b7e228ba3
commit
78b50806e3
@ -1,24 +1,38 @@
|
||||
export function twoSumHashTable(nums: number[], target: number): number[] {
|
||||
const result: number[] = [];
|
||||
const hashTable: Record<string, number> = {};
|
||||
let i = 0;
|
||||
// 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);
|
||||
// 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;
|
||||
}
|
||||
// if (searchKey in hashTable) {
|
||||
// result.push(hashTable[searchKey]);
|
||||
// result.push(val);
|
||||
// break;
|
||||
// } else {
|
||||
// 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