Skip to content

Commit 2c24c86

Browse files
author
bhan
committed
3sum solution
1 parent 6945bd0 commit 2c24c86

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

3sum/byol-han.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*/
5+
var threeSum = function (nums) {
6+
// 오름차순 정렬
7+
nums.sort((a, b) => a - b);
8+
const result = [];
9+
10+
for (let i = 0; i < nums.length - 2; i++) {
11+
// 중복된 숫자는 스킵
12+
if (i > 0 && nums[i] === nums[i - 1]) continue;
13+
14+
let left = i + 1;
15+
let right = nums.length - 1;
16+
17+
while (left < right) {
18+
const sum = nums[i] + nums[left] + nums[right];
19+
20+
if (sum < 0) {
21+
left++;
22+
} else if (sum > 0) {
23+
right--;
24+
} else {
25+
result.push([nums[i], nums[left], nums[right]]);
26+
// 중복된 left,right 값 스킵
27+
while (left < right && nums[left] === nums[left + 1]) left++;
28+
while (left < right && nums[right] === nums[right - 1]) right--;
29+
30+
left++;
31+
right--;
32+
}
33+
}
34+
}
35+
return result;
36+
};

0 commit comments

Comments
 (0)