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]
]
采用与15题相同的思路,只不过,这里是先确定两个数,然后用双指针法。
C++
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>>result;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++){
for(int j=i+1;j<nums.size();j++){
int low=j+1,high=nums.size()-1;
int tempsum=-nums[i]-nums[j]+target;
while(low<high){
if(nums[low]+nums[high]==tempsum){
vector<int>temp;
temp.push_back(nums[i]);temp.push_back(nums[j]);
temp.push_back(nums[low]);temp.push_back(nums[high]);
result.push_back(temp);
while(low<high&&nums[low+1]==nums[low])
low++;
low++;
while(low<high&&nums[high]==nums[high-1])
high--;
high--;
}
else if(nums[low]+nums[high]<tempsum)
low++;
else
high--;
}
while(j<nums.size()-1&&nums[j]==nums[j+1])
j++;
}
while(i<nums.size()-1&&nums[i]==nums[i+1])
i++;
}
return result;
}
};
Python
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
ans = []
if len(nums) < 4:
return ans
nums.sort()
for i in range(len(nums)):
if i != 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1, len(nums)):
if j != i+1 and nums[j] == nums[j-1]:
continue
low, high = j+1, len(nums)-1
temp = nums[i] + nums[j]
while low < high:
tempsum = temp + nums[low] + nums[high]
if tempsum == target:
ans.append([nums[i], nums[j], nums[low], nums[high]])
while low < high and nums[low] == ans[-1][2]:
low += 1
elif tempsum > target:
high -= 1
else:
low += 1
return ans