Skip to content

Commit 7d55fce

Browse files
committed
js16-leetcode-1-two-sum-optimized
1 parent 6d4da38 commit 7d55fce

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
var twoSum = function (nums, target) {
7+
// Map from number → its index in nums
8+
const seen = new Map();
9+
10+
for (let i = 0; i < nums.length; i++) {
11+
const complement = target - nums[i];
12+
// Have we already seen the complement?
13+
if (seen.has(complement)) {
14+
// Yes: return [index of complement, current index]
15+
return [seen.get(complement), i];
16+
}
17+
// Otherwise, record this number and its index
18+
seen.set(nums[i], i);
19+
}
20+
21+
// Problem guarantees exactly one solution, so we should never reach here
22+
return [];
23+
};
24+
25+
console.log(twoSum([2, 7, 11, 15], 9)); //[0,1]
26+
console.log(twoSum([3, 2, 4], 6)); //[1,2]
27+
28+
//overall time is O(n), with O(n) extra space for the map

0 commit comments

Comments
 (0)