18. 4Sum -- 找到数组中和为target的4个数

时间:2024-06-30 22:35:20

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int l = nums.size(), sum, left, right, i, j;
vector<vector<int>> ans;
if (l<)
return ans;
sort(nums.begin(), nums.end());
for (i = ; i<l - ; i++)
{
if(i && nums[i] == nums[i-])
continue;
for (j = i + ; j<l - ; j++)
{
if(nums[i]+nums[j]+nums[j+]+nums[j+]>target)
break;
if(nums[i]+nums[j]+nums[l-]+nums[l-]<target)
continue;
if (j>i + && nums[j] == nums[j - ])
continue;
sum = nums[i] + nums[j];
left = j + ;
right = l - ;
while (left < right)
{
if (sum + nums[left] + nums[right] == target)
ans.push_back({ nums[i], nums[j], nums[left++], nums[right--] });
else if (sum + nums[left] + nums[right] < target)
left++;
else
right--;
while (left>j+ && nums[left] == nums[left - ])
left++;
while(right<l- && nums[right] == nums[right + ])
right--;
}
}
}
return ans;
}
};