18. 4Sum
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.
Example:
Given array nums = [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]
]
solutions:
本题意是要求给定n个整数的数组num和一个整数目标,那么num中是否有元素a、b、c和d,使得a+b+c+d=目标值?在给出目标和的数组中找到所有唯一的四胞胎。
先将数组排序,第一第二个元素循环遍历,第三第四可以比较sum和target的大小,选择向那个方向进行遍历。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
if(nums.size() < 4)
return res;
for(int first = 0; first < nums.size() - 3; first++) {
if(first != 0 && nums[first] == nums[first - 1])
continue;
for(int second = first + 1; second < nums.size() - 2; second++) {
if(second != first + 1 && nums[second] == nums[second - 1])
continue;
int left = second + 1;
int right = nums.size() - 1;
while(left < right) {
int sum = nums[first] + nums[second] + nums[left] + nums[right];
if(sum < target)
left++;
else if(sum > target)
right--;
else {
res.push_back({nums[first], nums[second], nums[left], nums[right]});
left++;
while(left < right && nums[left] == nums[left - 1]) {
left++;
}
}
}
}
}
return res;
}
};