Skip to content

Commit f5d85e4

Browse files
committed
solve(w02): 15. 3Sum
1 parent f71a743 commit f5d85e4

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

3sum/jeongwoo903.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* 투 포인터 방식 사용
3+
* 시간 복잡도: O(n^2)
4+
* 공간 복잡도; O(n^2)
5+
*/
6+
7+
/**
8+
* @param {number[]} nums
9+
* @return {number[][]}
10+
*/
11+
const threeSum = (nums) => {
12+
const sorted = [...nums].sort((a, b) => a - b);
13+
const results = [];
14+
15+
sorted.forEach((val, i) => {
16+
if (i > 0 && val === sorted[i - 1]) return;
17+
18+
let left = i + 1;
19+
let right = sorted.length - 1;
20+
21+
while (left < right) {
22+
const sum = val + sorted[left] + sorted[right];
23+
24+
if (sum === 0) {
25+
results.push([val, sorted[left], sorted[right]]);
26+
27+
// 중복된 left/right 스킵
28+
const currentLeft = sorted[left];
29+
const currentRight = sorted[right];
30+
31+
while (left < right && sorted[left] === currentLeft) left++;
32+
while (left < right && sorted[right] === currentRight) right--;
33+
} else if (sum < 0) {
34+
left++;
35+
} else {
36+
right--;
37+
}
38+
}
39+
});
40+
41+
return results;
42+
};

0 commit comments

Comments
 (0)