四数之和

题目:

给定一个包含 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>> res = new ArrayList<>();
        if (nums == null || nums.length < 4) {
            return res;
        }
         Arrays.sort(nums);
        int len = nums.length;
        for(int i =0;i < len - 3 ;++i){
            if(i > 0 && nums[i] == nums[i -1]){
                continue;
            }
            for(int j = i + 1;j < len - 2 ;++j){
                if(j > i+1&&nums[j]== nums[j -1]){
                continue;
            }
                int start = j + 1;
                int end = len - 1;
                while(start < len){
                    int sum = nums[i] + nums[j] + nums[start] + nums[end];
                    if(sum == target){
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[start]);
                        list.add(nums[end]);
                        res.add(list);
                        while(start < end && nums[start] == nums[start + 1]){
                            ++start;
                        }
                        while(start < end && nums[end] == nums[end -1]){
                            --end;
                        }
                        ++start;
                        --end;
                        }else if(sum < target){
                             ++start;
                         }else{
                             --end;
                    }
                }
            }
        }
        return res;
    }
}


原文地址:https://www.cnblogs.com/youdiaodaxue16/p/10759528.html