给你一个由 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:
输入:nums = [1,0,-1,0,-2,2], target = 0 输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,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
首先枚举a,内部就是一个三数之和,参考:三数之和
对a进行去重:针对已经遍历过的a去重,nums[a] == nums[a-1],不能是nums[a+1],因为nums[a+1]可能是b
枚举b,内部就是一个两数之和:参考:两数之和
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
int length = nums.length;
for (int a = 0; a < length - 3; a++) {// 枚举a
long tmpA = nums[a];
if (a > 0 && tmpA == nums[a - 1])
continue;// 对a去重
// 最小的4个数相加大于target,则直接跳出,没戏了
if (tmpA + nums[a + 1] + nums[a + 2] + nums[a + 3] > target) {
break;
}
// 最大的三个数相加小于target,则进入a枚举的下一轮循环
if (tmpA + nums[length - 1] + nums[length - 2] + nums[length - 3] < target) {
continue;
}
// 枚举b
for (int b = a + 1; b < length - 2; b++) {
long tmpB = nums[b];
if (b > a + 1 && tmpB == nums[b - 1])
continue;// 对b去重
if (tmpA + tmpB + nums[b + 1] + nums[b + 2] > target) {
break;// 固定a后的最小的4个数字相加大于target,直接跳出
}
if (tmpA + tmpB + nums[length - 1] + nums[length - 2] < target) {
continue;// 固定a后最大的4个数字之和小于target,进入b枚举的下一轮循环
}
// 第三第四个数字寻找:c和d,由于固定了a和b,所以接下来类似两数之和
int c = b + 1;
int d = length - 1;
while (c < d) {
long tmpC = nums[c];
long tmpD = nums[d];
long sum = tmpA + tmpB + tmpC + tmpD;
if (sum > target) {
d--;// 把d变小
} else if (sum < target) {
c++;// 把c变大
} else {// 满足条件的cd二元组
//注意:返回的是integer类型的,所以强转为int
list.add(List.of((int) tmpA, (int) tmpB, (int) tmpC, (int) tmpD));
//对c和d去重
c++;
while (c < d && nums[c] == nums[c - 1]) {
c++;
}
d--;
while (d > c && nums[d] == nums[d + 1]) {
d--;
}
}
}
}
}
return list;
}
}