Skip to content

Commit f81a82c

Browse files
committed
solve: two sum
1 parent 6388615 commit f81a82c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

two-sum/wogha95.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// 2차: index를 값으로 갖는 Map을 활용하여 한번의 순회로 답안 도출
2+
// TC: O(N)
3+
// SC: O(N)
4+
5+
/**
6+
* @param {number[]} nums
7+
* @param {number} target
8+
* @return {number[]}
9+
*/
10+
var twoSum = function (nums, target) {
11+
const valueIndexMap = new Map();
12+
13+
for (let index = 0; index < nums.length; index++) {
14+
const value = nums[index];
15+
const anotherValue = target - value;
16+
17+
if (valueIndexMap.has(anotherValue)) {
18+
return [index, valueIndexMap.get(anotherValue)];
19+
}
20+
21+
valueIndexMap.set(value, index);
22+
}
23+
};
24+
25+
// 1차: 정렬 후 투포인터 활용
26+
// TC: O(N * logN)
27+
// SC: O(N)
28+
29+
/**
30+
* @param {number[]} nums
31+
* @param {number} target
32+
* @return {number[]}
33+
*/
34+
var twoSum = function (nums, target) {
35+
const sortedNums = nums
36+
.map((value, index) => ({ value, index }))
37+
.sort((a, b) => a.value - b.value);
38+
let left = 0;
39+
let right = sortedNums.length - 1;
40+
41+
while (left < right) {
42+
const sum = sortedNums[left].value + sortedNums[right].value;
43+
if (sum < target) {
44+
left += 1;
45+
} else if (sum > target) {
46+
right -= 1;
47+
} else {
48+
return [sortedNums[left].index, sortedNums[right].index];
49+
}
50+
}
51+
};

0 commit comments

Comments
 (0)