-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0018-4sum.js
More file actions
53 lines (44 loc) · 1.89 KB
/
0018-4sum.js
File metadata and controls
53 lines (44 loc) · 1.89 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
/**
* 4sum
* Time Complexity: O(N^3)
* Space Complexity: O(1)
*/
var fourSum = function (inputNumbers, desiredTarget) {
const arrayLength = inputNumbers.length;
const foundQuadruplets = [];
if (arrayLength < 4) {
return foundQuadruplets;
}
inputNumbers.sort((valA, valB) => valA - valB);
for (let indexOne = 0; indexOne < arrayLength - 3; indexOne++) {
if (indexOne > 0 && inputNumbers[indexOne] === inputNumbers[indexOne - 1]) {
continue;
}
for (let indexTwo = indexOne + 1; indexTwo < arrayLength - 2; indexTwo++) {
if (indexTwo > indexOne + 1 && inputNumbers[indexTwo] === inputNumbers[indexTwo - 1]) {
continue;
}
let leftPointer = indexTwo + 1;
let rightPointer = arrayLength - 1;
while (leftPointer < rightPointer) {
const currentSum = inputNumbers[indexOne] + inputNumbers[indexTwo] + inputNumbers[leftPointer] + inputNumbers[rightPointer];
if (currentSum === desiredTarget) {
foundQuadruplets.push([inputNumbers[indexOne], inputNumbers[indexTwo], inputNumbers[leftPointer], inputNumbers[rightPointer]]);
let distinctLeftValue = inputNumbers[leftPointer];
while (leftPointer < rightPointer && inputNumbers[leftPointer] === distinctLeftValue) {
leftPointer++;
}
let distinctRightValue = inputNumbers[rightPointer];
while (leftPointer < rightPointer && inputNumbers[rightPointer] === distinctRightValue) {
rightPointer--;
}
} else if (currentSum < desiredTarget) {
leftPointer++;
} else {
rightPointer--;
}
}
}
}
return foundQuadruplets;
};