-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy paththreeSum.js
57 lines (48 loc) · 1002 Bytes
/
threeSum.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
/**
* 三数之和
*/
function threeEqualZero(nums, third, results) {
if (nums.length < 2) {
return;
}
const record = new Set();
let i = 0;
let j = nums.length - 1;
while (i < j) {
const first = nums[i];
const second = nums[j];
if (first + second + third > 0) {
j = j - 1;
}
else if (first + second + third < 0) {
i = i + 1;
}
else {
if (!record.has(first)) {
record.add(first);
results.push([first, second, third]);
}
i = i + 1;
}
}
}
export function threeSum(nums) {
if (!Array.isArray(nums)) {
throw new Error('nums must be an array');
}
if (nums.length < 3) {
return [];
}
nums.sort((a, b) => a - b);
const results = [];
const record = new Set();
for (let i = 0; i < nums.length; i++) {
const third = nums[i];
if (record.has(third)) {
continue;
}
record.add(third);
threeEqualZero(nums.slice(i + 1), third, results);
}
return results;
}