-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path0018-4sum.js
59 lines (53 loc) · 1.31 KB
/
0018-4sum.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
/**
* 18. 4Sum
* https://leetcode.com/problems/4sum/
* Difficulty: Medium
*
* Given an array nums of n integers, return an array of all the unique
* quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
* - 0 <= a, b, c, d < n
* - a, b, c, and d are distinct.
* - nums[a] + nums[b] + nums[c] + nums[d] == target
*
* You may return the answer in any order.
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
const result = [];
nums.sort((a, b) => a - b);
for (let i = 0; i < nums.length - 3; i++) {
for (let j = i + 1; j < nums.length - 2; j++) {
let high = nums.length - 1;
let low = j + 1;
while (low < high) {
const sum = nums[i] + nums[j] + nums[low] + nums[high];
if (sum === target) {
result.push([nums[i], nums[j], nums[low], nums[high]]);
while (nums[low] === nums[low + 1]) {
low++;
}
while (nums[high] === nums[high - 1]) {
high--;
}
low++;
high--;
} else if (sum < target) {
low++;
} else {
high--;
}
}
while (nums[j] === nums[j + 1]) {
j++;
}
}
while (nums[i] === nums[i + 1]) {
i++;
}
}
return result;
};