-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15-Four-number-sum.js
63 lines (54 loc) · 1.48 KB
/
15-Four-number-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
52
53
54
55
56
57
58
59
60
61
62
63
function fourNumberSum(array, targetSum) {
// Write your code here.
array.sort((a, b) => a - b);
let leftPointer = 0;
let rightPointer = 0;
let result = [];
for (let i = 0; i < array.length - 3; i++) {
if (i != 0 && array[i] === array[i - 1]) {
continue;
}
for (let j = i + 1; j < array.length - 2; j++) {
if (j != i + 1 && array[j] === array[j - 1]) {
continue;
}
leftPointer = j + 1;
rightPointer = array.length - 1;
while (leftPointer < rightPointer) {
const sum =
array[i] + array[j] + array[leftPointer] + array[rightPointer];
if (sum < targetSum) {
leftPointer++;
}
if (sum > targetSum) {
rightPointer--;
}
if (sum === targetSum) {
result.push([
array[i],
array[j],
array[leftPointer],
array[rightPointer],
]);
leftPointer++;
rightPointer--;
while (
leftPointer < rightPointer &&
array[leftPointer] === array[leftPointer + 1]
) {
leftPointer++;
}
while (
leftPointer < rightPointer &&
array[rightPointer] === array[rightPointer + 1]
) {
rightPointer--;
}
}
}
}
}
return result;
}
// Do not edit the line below.
exports.fourNumberSum = fourNumberSum;