Description
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]
]
分析
- 这里的思路也很简单,先对nums排序,然后遍历nums,找到符合条件的四个数,然后放在set集合里面,set有一个好处是,它可以去重,这样就得到了所有的答案。
- 其实就是2sum,3sum的变形,多了循环遍历而已
C++代码
O(n3) time complexity
O(1) space complexity
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
set<vector<int>> result;
vector<vector<int>> ans;
if(nums.size()<4){
return ans;
}
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size()-3;i++){
for(int j=i+1;j<nums.size()-2;j++){
int left=j+1;
int right=nums.size()-1;
while(left<right){
int sum=nums[i]+nums[j]+nums[left]+nums[right];
if(sum==target){
vector<int> vec{nums[i],nums[j],nums[left],nums[right]};
result.insert(vec);
left++;
right--;
}else if(sum>target){
right--;
}else{
left++;
}
}
}
}
return vector<vector<int>>(result.begin(),result.end());
}
};
Python代码
4sum的重复情况比较复杂,要考虑第一个数的重复,第二个数的重复,还要考虑第三个数的重复,第四个数的重复,总之,所有的数的重复的情况都要考虑,我写的时候在第二个数重复的限制条件上翻车了,写博客吸取经验,借鉴一下。
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
res=[]
for i in range(len(nums)-3):
if i>0 and nums[i]==nums[i-1]:
continue
for j in range(i+1,len(nums)-2):
if j>i+1 and nums[j]==nums[j-1]:
continue
left= j+1
right = len(nums)-1
t=nums[i]+nums[j]
while left<right:
val = t+nums[left]+nums[right]
if val==target:
res.append([nums[i],nums[j],nums[left],nums[right]])
while left<right and nums[left]==nums[left+1]:
left+=1
while left<right and nums[right]==nums[right-1]:
right-=1
left+=1
right-=1
elif val>target:
right-=1
else:
left+=1
return res