forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0015-3sum.js
34 lines (31 loc) · 795 Bytes
/
0015-3sum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
const res = [];
nums.sort((a,b) => a-b)
for (let i = 0; i < nums.length; i++) {
const a = nums[i];
if (a > 0) break;
if (i > 0 && a === nums[i - 1]) continue;
let l = i + 1;
let r = nums.length - 1;
while (l < r) {
const threeSum = a + nums[l] + nums[r];
if (threeSum > 0) {
r--;
} else if (threeSum < 0) {
l++;
} else {
res.push([a, nums[l], nums[r]]);
l++;
r--;
while (nums[l] === nums[l - 1] && l < r) {
l++;
}
}
}
}
return res;
}