LeetCode18. 四数之和
描述
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:答案中不可以包含重复的四元组。
示例
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
提示
0 <= nums.length <= 200
- − 1 0 9 < = n u m s [ i ] < = 1 0 9 -10^9 <= nums[i] <= 10^9 −109<=nums[i]<=109
- − 1 0 9 < = t a r g e t < = 1 0 9 -10^9 <= target <= 10^9 −109<=target<=109
分析
排序+双指针将复杂度从 O ( N 4 ) O(N^4) O(N4)降到 O ( N 3 ) O(N^3) O(N3)
代码
public List<List<Integer>> fourSum(int[] nums, int target) {
ArrayList<List<Integer>> res = new ArrayList<>();
int len=nums.length;
if (len<4)
return res;
Arrays.sort(nums);
for (int i=0;i<len;i++){
if (i>0&&nums[i-1]==nums[i])
continue;
for (int j=i+1;j<len;j++){
if (j>i+1&&nums[j]==nums[j-1])
continue;
int left=j+1,right=len-1;
while (left<right){
int sum=nums[i]+nums[j]+nums[left]+nums[right];
if (sum==target){
res.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
//两个while用于后两位数去重
while (left<right&&nums[left]==nums[left+1])
left++;
left++;
while (left<right&&nums[right]==nums[right-1])
//此处如果使用nums[right]==nums[right+1] 可能会造成下标越界
right--;
right--;
}else if (sum<target){
left++;
}else {
right--;
}
}
}
}
return res;
}