-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.3-sum.js
51 lines (41 loc) · 1.16 KB
/
15.3-sum.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
// Source : https://leetcode.com/problems/3sum/
// Author : Han Zichi
// Date : 2017-10-08
// Complexity: O(n^2)
/**
* @param {number[]} nums
* @return {number[][]}
*/
/* sorted three sum*/
var threeSum = function (nums) {
nums.sort((a, b) => a - b);
let ans = [];
let len = nums.length;
// enumerate 列舉 the array, and assume the item to be the smallest one
for (let i = 0; i < len; i++) {
// have already enumerate the item as the smallest one among the three
// then continue
if (i && nums[i] === nums[i - 1]) continue;
// the sum of another two should be
let target = -nums[i];
// the indexes of another two
let [start, end] = [i + 1, len - 1];
while (start < end) {
let sum = nums[start] + nums[end];
if (sum > target) {
end--;
} else if (sum < target) {
start++;
} else {
ans.push([nums[i], nums[start], nums[end]]);
// remove the duplication
while (nums[start] === nums[start + 1]) start++;
start++;
// remove the duplication
while (nums[end] === nums[end - 1]) end--;
end--;
}
}
}
return ans;
};