-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreeSum.js
More file actions
59 lines (53 loc) · 1.47 KB
/
threeSum.js
File metadata and controls
59 lines (53 loc) · 1.47 KB
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
function twoSum(sumArray, nums, parentIndex) {
let smallIndex = parentIndex + 1,
bigIndex = nums.length - 1,
parentNum = nums[parentIndex];
while (smallIndex < bigIndex) {
let smallNum = nums[smallIndex],
bigNum = nums[bigIndex];
let sum = smallNum + bigNum + parentNum;
if (sum > 0) {
bigIndex--;
while (nums[bigIndex] === nums[bigIndex + 1]) {
bigIndex--;
}
continue;
}
if (sum < 0) {
smallIndex++;
while (nums[smallIndex] === nums[smallIndex - 1]) {
smallIndex++;
}
continue;
}
if (sum === 0) {
sumArray.push([smallNum, bigNum, parentNum]);
bigIndex--;
while (nums[bigIndex] === nums[bigIndex + 1]) {
bigIndex--;
}
smallIndex++;
while (nums[smallIndex] === nums[smallIndex - 1]) {
smallIndex++;
}
continue;
}
}
}
function threeSum(nums) {
let length = nums.length,
sumArray = [];
nums.sort((a, b) => a - b);
for (let ii = 0; ii < length - 2; ii++) {
let parentNum = nums[ii];
if (parentNum > 0 && ii !== 0) {
break;
}
if (parentNum === nums[ii - 1]) {
continue;
} else {
twoSum(sumArray, nums, ii);
}
}
return sumArray;
}