-
Notifications
You must be signed in to change notification settings - Fork 0
/
0015-3Sum.js
53 lines (46 loc) · 1.4 KB
/
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//-----------------------------------------------------------------------------
// Runtime: 128ms
// Memory Usage: 47.5 MB
// Link: https://leetcode.com/submissions/detail/385383405/
//-----------------------------------------------------------------------------
var solution = function() {
'use strict';
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
nums.sort((a, b) => a - b);
let N = nums.length;
let results = [];
for (let i = 0; i < N - 2 && nums[i] <= 0; i++)
{
let lo = i + 1, hi = N - 1;
while (lo < hi && nums[hi] >= 0)
{
let sum = nums[i] + nums[lo] + nums[hi];
if (sum === 0) {
results.push([ nums[i], nums[lo], nums[hi] ]);
}
if (sum <= 0) {
do {
lo++;
} while (lo < hi && nums[lo - 1] === nums[lo]);
}
if (sum >= 0) {
do {
hi--;
} while (lo < hi && nums[hi] === nums[hi + 1]);
}
}
while (i < N - 2 && nums[i] === nums[i + 1]) {
i++;
}
}
return results;
};
return {
threeSum: threeSum
};
};
module.exports = solution();