Skip to content

Commit 7ee5ca1

Browse files
committed
two sum solution
1 parent c10802e commit 7ee5ca1

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

two-sum/JangAyeon.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
7+
// 첫번째 통과 풀이 - 브루트포스
8+
var twoSum = function (nums, target) {
9+
for (let i = 0; i < nums.length; i++) {
10+
for (let j = i + 1; j < nums.length; j++) {
11+
if (nums[i] + nums[j] == target) {
12+
return [i, j];
13+
}
14+
}
15+
}
16+
};
17+
18+
// 두번째 통과 풀이 - 해시맵 + 효율성 고려
19+
var twoSum = function (nums, target) {
20+
const map = new Map(); // {값: 인덱스}
21+
22+
for (let i = 0; i < nums.length; i++) {
23+
const complement = target - nums[i]; // 필요한 짝 계산
24+
if (map.has(complement)) {
25+
return [map.get(complement), i]; // 이전에 complement가 있었으면 바로 반환
26+
}
27+
map.set(nums[i], i);
28+
}
29+
};

0 commit comments

Comments
 (0)