【题目】
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.
【思路】
和leetcode15三数之和3 Sum类似https://www.cnblogs.com/inku/p/9955638.html
多一次循环,加粗部分是新增的
重点是去重。
【代码】
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> data=new ArrayList<>();
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
for(int j=nums.length-1;j>0;j--){
int left=i+1;
int right=j-1;
if(i>0&&nums[i]==nums[i-1]){
continue;}
if(j<nums.length-1&&nums[j]==nums[j+1]){
continue;}
while(left<right){
int sum=nums[left]+nums[right]+nums[i]+nums[j];
if(sum==target){
data.add(Arrays.asList(nums[left], nums[right],nums[i],nums[j]));
left++;
right--;
while(left<right&&nums[left]==nums[left-1])
left++;
while(left<right&&nums[right]==nums[right+1])
right--;
}
else if(left<right&&sum>target)
right--;
else
left++;
}
}
}
return data;
}
}