Skip to content

Commit b7514ac

Browse files
committed
feat: threeSum 문제 풀이 추가 - 정렬 및 투 포인터 방식 사용
1 parent 2f24f39 commit b7514ac

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

3sum/reach0908.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 시간복잡도: O(n²)
3+
* 공간복잡도: O(1) (결과 배열 제외)
4+
* 풀이 방법: 정렬 후 투 포인터 방식
5+
* @param {number[]} nums
6+
* @return {number[][]}
7+
*/
8+
const threeSum = function (nums) {
9+
const sortedNums = nums.sort((a, b) => a - b);
10+
const result = [];
11+
12+
for (let i = 0; i < sortedNums.length; i += 1) {
13+
// 첫 번째 요소의 중복 제거
14+
if (i > 0 && sortedNums[i] === sortedNums[i - 1]) {
15+
continue;
16+
}
17+
18+
let left = i + 1;
19+
let right = sortedNums.length - 1;
20+
21+
while (left < right) {
22+
const threeSum = sortedNums[i] + sortedNums[left] + sortedNums[right];
23+
24+
if (threeSum > 0) {
25+
right -= 1;
26+
} else if (threeSum < 0) {
27+
left += 1;
28+
} else {
29+
result.push([sortedNums[i], sortedNums[left], sortedNums[right]]);
30+
31+
// 중복 제거
32+
while (left < right && sortedNums[left] === sortedNums[left + 1]) {
33+
left += 1;
34+
}
35+
while (left < right && sortedNums[right] === sortedNums[right - 1]) {
36+
right -= 1;
37+
}
38+
39+
left += 1;
40+
right -= 1;
41+
}
42+
}
43+
}
44+
45+
return result;
46+
};

0 commit comments

Comments
 (0)