Skip to content

Commit 5d7ed3f

Browse files
committed
two-sum
1 parent e0b014b commit 5d7ed3f

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

two-sum/taewanseoul.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* 1. Two Sum
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+
* https://leetcode.com/problems/two-sum/description/
8+
*/
9+
function twoSum(nums: number[], target: number): number[] {
10+
const map = new Map<number, number>();
11+
12+
for (let i = 0; i < nums.length; i++) {
13+
if (map.has(target - nums[i])) {
14+
return [i, map.get(target - nums[i])!];
15+
}
16+
map.set(nums[i], i);
17+
}
18+
}
19+
20+
// O(n) time
21+
// O(n) space

0 commit comments

Comments
 (0)