Leetcode 18 四数之和
2019-10-31 本文已影响0人
hekirakuno
给定一个包含 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]
]
思路:这种几数之和的感觉思路都差不多,固定某些值,将实际操作转化为双指针,三数之和是固定一个数,这边就是固定两个数。去重需要注意一下。在两层循环中都要考虑到,不然就会漏值或者少去重。
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
Arrays.sort(nums);
if(nums.length<4){
//没有符合要求的四个数
return ans;
}
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;j++){
if(j>i+1&&nums[j]==nums[j-1]){
continue;
}
int l = j+1;
int r = nums.length-1;
while(l<r){
int sum = nums[i]+nums[j]+nums[l]+nums[r];
if(r<nums.length-1&&nums[r]==nums[r+1]||sum>target){
r--;
}else
if(l>j+1&&nums[l]==nums[l-1]||sum<target){
l++;
}else {
List<Integer> temp = new ArrayList<Integer>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[l++]);
temp.add(nums[r--]);
ans.add(temp);
}
}
}
}
return ans;
}
}