-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.js
55 lines (53 loc) · 1.21 KB
/
18.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
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
nums = nums.sort((a, b) => a - b);
let res = [];
let length = nums.length;
let j;
let l, r, value;
for (let i = 0; i < length - 3; i++) {
for (j = i + 1; j < length - 2; j++) {
l = j + 1;
r = length - 1;
while (l < r) {
value = nums[i] + nums[j] + nums[l] + nums[r];
if (value === target) {
res.push([nums[i], nums[j], nums[l], nums[r]]);
r--;
l++;
while (nums[r + 1] === nums[r]) {
r--;
}
while (nums[l - 1] === nums[l]) {
l++;
}
} else if (value > target) {
r--;
while (nums[r + 1] === nums[r]) {
r--;
}
} else {
l++;
while (nums[l - 1] === nums[l]) {
l++;
}
}
}
while (nums[j + 1] === nums[j]) {
j++;
}
}
while (nums[i] === nums[i + 1]) {
i++;
}
}
return res;
};
// [1,0,-1,0,-2,2]
// 0
console.log(fourSum([-3, -2, -1, 0, 0, 1, 2, 3], 0));
debugger;