-
Notifications
You must be signed in to change notification settings - Fork 33
/
015-3Sum.js
64 lines (55 loc) · 1.58 KB
/
015-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
54
55
56
57
58
59
60
61
62
63
64
/**
* https://leetcode.com/problems/3sum/
* Difficulty:Medium
*
* Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
* Find all unique triplets in the array which gives the sum of zero.
* Note: The solution set must not contain duplicate triplets.
*
* For example, given array S = [-1, 0, 1, 2, -1, -4],
* A solution set is:
* [
* [-1, 0, 1],
* [-1, -1, 2]
* ]
*/
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
nums.sort(function (a, b) {
if (a > b) return 1;
if (a === b) return 0;
if (a < b) return -1;
});
// console.log(nums);
var ret = [];
for (var i = 0; i < nums.length - 2; i++) {
var a = nums[i];
if (i === 0 || (i > 0 && nums[i] !== nums[i - 1])) {
var j = i + 1;
var k = nums.length - 1;
while (j < k) {
var b = nums[j];
var c = nums[k];
var sum = a + b + c;
// console.log(a, b, c, '=', sum);
if (sum > 0) k--;
else if (sum === 0) {
ret.push([a, b, c]);
while (j < k && nums[j] === nums[++j]);
while (j < k && nums[k] === nums[--k]);
// j++;
// k--;
}
else j++;
}
}
}
return ret;
};
console.log(threeSum([-2, 0, 0, 2, 2]));
console.log(threeSum([-1, 0, 1, 2, -1, -4]));
// console.log(threeSum([0, 0, 0, 0]));
// console.log(threeSum([1, -1, -1, 0]));