给你一个由 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
思路和三数之和差不多,就是多加了一层for循环。
题库的有两个测试例子需要注意:
1、输入:
nums =
[1000000000,1000000000,1000000000,1000000000]
target =
0
解决方法
if (size < 4 || (target >= 0 && nums[0] > target) ||
(target < 0 && nums[size - 1] < target)) {
return res;
}
判断数组长度,nums最小值(这里的nums经过排序)是不是大于target,nums最大值是不是小于target,满足任意一个都直接结束程序
2、输入
nums =
[0,0,0,1000000000,1000000000,1000000000,1000000000]
target =
1000000000
解决方法:
long val =(long)nums[i] + nums[j] + nums[left] + nums[right];
先把(int)nums[i]
转为(long)nums[i]
,防止加法运算中出现数据溢出的情况。具体看这里➡数据溢出signed integer overflow 2000000000+1000000000 cannot be represented in type ‘value_type‘-CSDN博客
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int size = nums.size();
vector<vector<int>> res;
res.reserve(size > 128 ? 128 : 0);
sort(nums.begin(), nums.end());
int left;
int right;
if (size < 4 || (target >= 0 && nums[0] > target) ||
(target < 0 && nums[size - 1] < target)) {
return res;
}
for (int i = 0; i < size - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < size - 1; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
left = j + 1;
right = size - 1;
while (left < right) {
long val =
(long)nums[i] + nums[j] + nums[left] + nums[right];
if (val > target) {
right--;
continue;
} else if (val < target) {
left++;
continue;
} else {
vector<int> temp{nums[i], nums[j], nums[left],
nums[right]};
res.push_back(temp);
right--;
left++;
while (nums[left] == nums[left - 1] && left < right) {
left++;
}
while (nums[right] == nums[right + 1] && left < right) {
right--;
}
}
}
}
}
return res;
}
};