Skip to content

Commit 1c441d1

Browse files
committed
two sum solution
1 parent cd4e26b commit 1c441d1

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

two-sum/Wonjuny0804.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
3+
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
4+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
5+
You can return the answer in any order.
6+
7+
Example 1:
8+
9+
Input: nums = [2,7,11,15], target = 9
10+
Output: [0,1]
11+
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
12+
13+
Example 2:
14+
15+
Input: nums = [3,2,4], target = 6
16+
Output: [1,2]
17+
18+
Example 3:
19+
20+
Input: nums = [3,3], target = 6
21+
Output: [0,1]
22+
23+
*/
24+
25+
function twoSum(nums: number[], target: number): number[] {
26+
const map = new Map();
27+
28+
for (let i = 0; i < nums.length; i++) {
29+
const diff = target - nums[i];
30+
if (map.has(nums[i])) return [map.get(nums[i]), i];
31+
else map.set(diff, i);
32+
}
33+
34+
return [];
35+
}

0 commit comments

Comments
 (0)