Skip to content

Commit 25bcb9c

Browse files
authored
[ PS ] : 3Sum
1 parent 7278a49 commit 25bcb9c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

3sum/uraflower.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 주어진 배열 중 세 원소의 합이 0인 고유한 경우를 반환하는 함수
3+
* @param {number[]} nums
4+
* @return {number[][]}
5+
*/
6+
const threeSum = function(nums) {
7+
const answer = [];
8+
const sorted = nums.toSorted((a, b) => Number(a) - Number(b));
9+
10+
for (let i = 0; i < sorted.length; i++) {
11+
if (i > 0 && sorted[i] === sorted[i - 1]) continue;
12+
13+
let left = i + 1;
14+
let right = sorted.length - 1;
15+
while (left < right) {
16+
const sum = sorted[i] + sorted[left] + sorted[right];
17+
18+
if (sum > 0) right--;
19+
else if (sum < 0) left++;
20+
else {
21+
answer.push([sorted[i], sorted[left], sorted[right]]);
22+
right--;
23+
24+
// 중복 방지
25+
while (sorted[left] === sorted[left + 1] && left < right) left++;
26+
while (sorted[right] === sorted[right + 1] && left < right) right--;
27+
}
28+
}
29+
}
30+
31+
return answer;
32+
};
33+
34+
// 시간복잡도: O(n^2)
35+
// 공간복잡도: O(n)

0 commit comments

Comments
 (0)