给定一个包含 n 个整数的数组 nums
和一个目标值 target
,判断 nums
中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target
相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求的四元组集合为: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
减少时间:continue break
卡了很久的地方:
if(j-1>i && nums[j] == nums[j-1])
continue;
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums.length < 4)
return res;
Arrays.sort(nums);
int n = nums.length;
for(int i=0; i<n-3; i++){
if(i-1>=0 && nums[i] == nums[i-1])
continue;
//当前序列中最小的四个数加起来>target,结束循环
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target)
break;
//当前序列的最小数加上最大的三个数还是<target,应该增大最小数
if(nums[i]+nums[n-1]+nums[n-2]+nums[n-3]<target)
continue;
for(int j=i+1; j<n-2; j++){
if(j-1>i && nums[j] == nums[j-1])
continue;
int spare = target-nums[i]-nums[j];
if(nums[j+1]+nums[j+2] > spare)
break;
if(nums[n-1]+nums[n-2] < spare)
continue;
int l = j+1;
int r = n-1;
while(l<r){
if(nums[l]+nums[r] == spare){
res.add(Arrays.asList(nums[i],nums[j],nums[l],nums[r] ) );
while(l<r && nums[l]==nums[l+1])
l++;
while(l<r && nums[r]==nums[r-1])
r--;
l++;
r--;
}
else if(nums[l]+nums[r] < spare)
l++;
else
r--;
}
}
}
return res;
}
}