算法-四数之和

leetcode-四数之和
https://leetcode-cn.com/problems/4sum/
坚持每天进步

四数之和

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] :

0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。

示例 1:

1
2
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

示例 2:

1
2
输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]

提示:

  • 1 <= nums.length <= 200
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109

解题思路

  • 定义双指针,避免暴力循环解题;
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 len = nums.length;
for (let i = 0; i < len - 2; i++) {

if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}

for (let j = i + 1; j < len - 2; j++) {

if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}

let firstNum = nums[i];
let secondNum = nums[j];

const restVal = target - firstNum - secondNum

let leftIndex = j + 1;
let rightIndex = len - 1;
while(leftIndex < rightIndex) {
let sum = nums[leftIndex] + nums[rightIndex];
if (restVal === sum) {

res.push([firstNum, secondNum, nums[leftIndex], nums[rightIndex]]);

while (nums[leftIndex] === nums[leftIndex + 1]) {
leftIndex++;
}
while (nums[rightIndex] === nums[rightIndex - 1]) {
rightIndex--;
}
leftIndex++;
rightIndex--;
} else if (sum < restVal) {
leftIndex++;
} else if (sum > restVal) {
rightIndex--;
}
}
}
}

return res;

};