题目描述: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.
解题思路:先将数组排序,固定两个数的位置的同时避免重复,若和大于目标,则将大数左移,若和小于目标,则将小数右移,若和等于目标,将这四个数加入列表,并将小数右移大数左移(注意避免重复)。
代码如下:
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
if(nums==null||nums.length<4) return result;
for(int i=0;i<nums.length-3;i++){
if(i>0&&nums[i]==nums[i-1]) continue;
for(int j=i+1;j<nums.length-2;j++){
if(j>(i+1)&&nums[j]==nums[j-1]) continue;
int low=j+1,high=nums.length-1;
int sum = target-nums[i]-nums[j];
while(low<high){
if(nums[low]+nums[high]==sum){
result.add(Arrays.asList(nums[i],nums[j],nums[low],nums[high]));
while(low<high&&nums[low]==nums[low+1]) low++;
while(low<high&&nums[high]==nums[high-1]) high--;
low++;
high--;
}else if(nums[low]+nums[high]<sum) low++;
else high--;
}
}
}
return result;
}
}