-
Notifications
You must be signed in to change notification settings - Fork 0
/
15-threeSum.js
100 lines (90 loc) · 2.81 KB
/
15-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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var threeSum = function (nums) {
if (nums.length < 3) {
return [];
}
let mergeSort = function (array) {
if (array.length === 0) {
return [];
}
let merge = function (firstArray, secondArray) {
let i = 0;
let j = 0;
let result = [];
while (true) {
if (firstArray[i] < secondArray[j]) {
result.push(firstArray[i]);
i++;
} else {
result.push(secondArray[j]);
j++;
}
if (i === firstArray.length) {
return result.concat(
secondArray.slice(j, secondArray.length)
);
} else if (j === secondArray.length) {
return result.concat(
firstArray.slice(i, firstArray.length)
);
}
}
};
if (array.length === 1) {
return array;
}
const middleIndex = Math.floor(array.length / 2);
const firstArray = mergeSort(array.slice(0, middleIndex));
const secondArray = mergeSort(array.slice(middleIndex, array.length));
const merged = merge(firstArray, secondArray);
return merged;
};
const twoSum = function (sorted, target) {
if (sorted.length === 0) {
return [];
}
let result = [];
let i = 0;
let j = sorted.length - 1;
while (true) {
let sum = sorted[i] + sorted[j];
if (sum > target) {
j--;
} else if (sum < target) {
i++;
} else {
let add = true;
result.forEach((el) => {
if (el[0] === sorted[i] && el[1] === sorted[j]) {
add = false;
}
});
if (add) {
result.push([sorted[i], sorted[j]]);
}
i++;
}
if (i >= j) {
return result;
}
}
};
const sorted = mergeSort(nums);
let result = [];
for (let i = 0; i < sorted.length; i++) {
if (sorted[i] !== sorted[i - 1]) {
let first = sorted[i];
// console.log(first);
let arr = sorted.slice(i + 1);
// console.log(arr);
if (arr.length >= 2) {
answers = twoSum(arr, 0 - first).map((el) => {
return [first].concat(el);
});
// console.log(answers);
result = result.concat(answers);
}
}
}
return result;
};
console.log(threeSum([-55,-24,-18,-11,-7,-3,4,5,6,9,11,23,33]));