Skip to content

Commit 7cf288b

Browse files
정도영정도영
authored andcommitted
3sum solution
1 parent 73e71b4 commit 7cf288b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

3sum/jdy8739.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*/
5+
var threeSum = function(nums) {
6+
const answer = [];
7+
8+
const sorted = nums.sort((a, b) => a - b);
9+
10+
for (let i=0; i<sorted.length; i++) {
11+
if (i > 0 && sorted[i] === sorted[i - 1]) {
12+
// 위 조건으로 중복 숫자 필터
13+
continue;
14+
}
15+
16+
let l = i + 1;
17+
let h = sorted.length - 1;
18+
19+
while (l < h) {
20+
const sum = sorted[i] + sorted[l] + sorted[h];
21+
22+
if (sum === 0) {
23+
const arr = [sorted[i], sorted[l], sorted[h]];
24+
answer.push(arr);
25+
26+
// 아래 반복문으로 중복 숫자 필터
27+
while (l < h && sorted[l] === sorted[l + 1]) l++;
28+
while (l < h && sorted[h] === sorted[h - 1]) h--;
29+
30+
h--;
31+
l++;
32+
}
33+
34+
if (sum > 0) h--;
35+
if (sum < 0) l++;
36+
}
37+
}
38+
39+
return answer;
40+
};
41+
42+
// TC: O(n2)
43+
// SC: O(1)
44+
45+

0 commit comments

Comments
 (0)