You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
877 B
TypeScript

// 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[] {
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 [];
};