Skip to content

Commit d905857

Browse files
author
jaehyunglee
committed
two-sum solution
1 parent a0fc481 commit d905857

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

β€Žtwo-sum/blossssom.tsβ€Ž

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param nums - μ •μˆ˜ λ°°μ—΄
3+
* @param target - nums 값을 더해 λ‚˜μ˜¬ κ°’
4+
* @returns - target을 λ§Œλ“œλŠ” index κ°’
5+
*
6+
* @description
7+
* 1. λ™μΌν•œ μš”μ†Œ λ‘λ²ˆ μ‚¬μš© κΈˆμ§€
8+
* 2. 각 μž…λ ₯에 λŒ€ν•΄ λͺ…ν™•ν•œ ν•˜λ‚˜μ˜ μ†”λ£¨μ…˜μ΄ μžˆλ‹€κ³  κ°€μ •
9+
*
10+
* @answer1
11+
* - O(n^2)
12+
*
13+
* @answer2
14+
* - O(n)
15+
*/
16+
17+
// function twoSum(nums: number[], target: number): number[] {
18+
// for (let i = 0; i < nums.length - 1; i++) {
19+
// for (let j = i + 1; j < nums.length; j++) {
20+
// if (nums[i] + nums[j] === target) {
21+
// return [i, j];
22+
// }
23+
// }
24+
// }
25+
// return [];
26+
// }
27+
28+
function twoSum(nums: number[], target: number): number[] {
29+
const map = new Map();
30+
31+
for (let i = 0; i < nums.length; i++) {
32+
if (map.has(target - nums[i])) {
33+
return [map.get(target - nums[i]), i];
34+
}
35+
map.set(nums[i], i);
36+
}
37+
return [];
38+
}

0 commit comments

Comments
Β (0)