12 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]
]
解题思路和前面三数加和也很近似,首先对数组进行排序,对头两个数用遍历的方法获得,最后两个数的确定则用两头逼近的方式。由此获得数组组合存在重复的问题,所以大部分时间都是在修复数组重复的BUG。。。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> ans{};
int len = nums.size();
if(len<4) return ans;
//sort
sort(nums.begin(),nums.end());
//edge conditions
int min = nums[0] + nums[1] + nums[2] + nums[3];
int max = nums[len-1] + nums[len-2] + nums[len-3] + nums[len-4];
if(target < min) return ans;
if(target > max) return ans;
//
int left,right;
int left_anchor,right_anchor;
for(int i = 0; i < len; i++)
{
if((i != 0) && (nums[i] == nums[i-1])) continue;
for(int j = i+1;j<len-2;j++)
{
if((j != i+1) && (nums[j] == nums[j-1])) continue;
left_anchor = i;
right_anchor = j;
left = right_anchor + 1;
right = len - 1;
while((left < right))
{
int temp = nums[left_anchor] + nums[right_anchor] + nums[left] + nums[right] ;
if(temp == target)
{
vector<int> temp_ans;
temp_ans.push_back(nums[left_anchor]);
temp_ans.push_back(nums[right_anchor]);
temp_ans.push_back(nums[left]);
temp_ans.push_back(nums[right]);
ans.push_back(temp_ans);
int temp_left = left;
int temp_right = right;
while((nums[temp_left] == nums[left]) && (temp_left < right))
{
temp_left++;
}
left = temp_left;
while((nums[temp_right] == nums[right]) && (temp_right > left))
{
temp_right--;
}
right = temp_right;
}
else if(temp < target) left++;
else right--;
}
}
}
return ans;
}
};