題目:4 Sum
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.
例子:
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]
]
問題解析:
給定數組,返回數組中和爲target的四元組。
鏈接:
思路標籤
算法:排序 + 雙指針
解答:
- 以LeetCode-15 & 16 的思想,我們使用兩個循環遍歷給出四元組中的前兩個候選,然後以雙指針的形式選擇剩下的兩個候選;
- 因爲數組是排序過的,所以我們可以分別在第一和第二個循環中判斷當前連續四個(三個)以及當前候選和最後的三個(兩個)候選的和與target比較,選擇循環的跳過和跳出;
- 同樣,我們需要注意循環中第一和第二個候選的重複問題,連續相同的候選選擇跳過操作;同樣也對符合條件的左右指針值進行跳過操作。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int> > ret;
int n = nums.size();
if(n<4) return ret;
sort(nums.begin(), nums.end());
for(int i=0; i<n-3; ++i){
if(i>0 && nums[i]==nums[i-1]) continue;
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target) break;
if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1] < target) continue;
for(int j=i+1; j<n-2; ++j){
if(j>i+1 && nums[j]==nums[j-1]) continue;
if(nums[i]+nums[j]+nums[j+1]+nums[j+2] > target) break;
if(nums[i]+nums[j]+nums[n-2]+nums[n-1] < target) continue;
int l = j+1, r = n-1;
while(l<r){
int tempsum = nums[i]+nums[j]+nums[l]+nums[r];
if(tempsum < target) l++;
else if (tempsum > target) r--;
else{
ret.push_back(vector<int>{nums[i], nums[j], nums[l], nums[r]});
do{
l++;
}while(nums[l] == nums[l-1] && l<r);
do{
r--;
}while(nums[r] == nums[r+1] && l<r);
}
}
}
}
return ret;
}
};