四数之和(大白话说思路)——数组专题
思路:不重复赘述,思路参照三数之和
重点就是边界和在遍历时跳过重复的数,直接上代码。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
vector<vector<int>>res;
for(int i=0;i<nums.size();){
auto v = treeSum(nums,i+1,target-nums[i]);
for(auto& it:v){
it.push_back(nums[i]);
sort(it.begin(),it.end());
res.push_back(it);
}
//跳过重复的数
int index = i;
while(i<nums.size()&&nums[index]==nums[i])index++;
i = index;
}
return res;
}
//从start开始
vector<vector<int>> treeSum(vector<int>&nums,int start,int target){
vector<vector<int>>ans;
for(int i=start;i<nums.size();){
for(int j =i+1,k=nums.size()-1;j<k;){
int cur = nums[i]+nums[j]+nums[k];
if(cur==target){
ans.push_back({nums[i],nums[j],nums[k]});
//跳过重复的数
int index = j;
while(index<nums.size()&&nums[index]==nums[j])index++;
j = index;
int index1 = k;
while(index1>=0&&nums[index1]==nums[k])index1--;
k = index1;
}
else if(cur<target){
//跳过重复的数
int index = j;
while(index<nums.size()&&nums[index]==nums[j])index++;
j = index;
}
else{
//跳过重复的数
int index = k;
while(index>=0&&nums[index]==nums[k])index--;
k = index;
}
}
int index = i;
while(i<nums.size()&&nums[index]==nums[i])index++;
i = index;
}
return ans;
}
};