题目分析:
这道题和2Sum类似,先固定两个数,再去从第二个数后开始从两头滑动,寻找到四个数和为target。但依然要注意的是重复的问题。实现代码如下:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target){
vector<vector<int>> res = {};
if (nums.size() < 4) return res;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 3; i++)
{
//跳过第一个固定数字的重复数字,注意是i>0
if ((i>0) && (nums[i] == nums[i - 1]))continue;
for (int j = i + 1; j < nums.size() - 2; j++)
{
int left = j + 1;
int right = nums.size() - 1;
//跳过第二个固定数的重复数字,注意是j>i+1
if ((j>i+1) && (nums[j] == nums[j - 1]))continue;
while (left < right)
{
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target)
{
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[j]);
tmp.push_back(nums[left]);
tmp.push_back(nums[right]);
res.push_back(tmp);
while ((nums[left++] == nums[left]) && (nums[right--] == nums[right]))
{
}
}
else if (sum < target)
{
while ((left < right) && (nums[left++] == nums[left]))//跳过重复的数字
{
}
}
else
{
while ((left < right) && (nums[right--] == nums[right]))//跳过重复的数字
{
}
}
}
}
}
return res;
}
};