leetcode18-四数之和

原题

给定一个包含 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]
]

解法

思想

可以参考leetcode15-三数之和的解法,再加一个指针,变成两指针循环、两指针移动。

代码

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(nums==null|| nums.length<4){
            return result;
        }
        Arrays.sort(nums);
        //第一个指针的移动范围
        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 second = j+1; // 从当前位置开始
                int third = nums.length-1; // 从尾部开始
                while(second<third){
                    int sum = nums[i]+nums[j]+nums[second]+nums[third];
                    if(sum == target){ // 找到该数组
                        result.add(Arrays.asList(nums[i],nums[j],nums[second],nums[third]));
                        //跳过相同的元素
                        while(second<third && nums[second] == nums[second+1]) second++;
                        while(second<third && nums[third] == nums[third-1]) third--;
                    }
                    if(sum > target) third--;
                    else second++;
                }
            }
        }
        return result;
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode18-%e5%9b%9b%e6%95%b0%e4%b9%8b%e5%92%8c/

(0)
彭晨涛彭晨涛管理者
上一篇 2020年5月4日
下一篇 2020年5月5日

相关推荐

发表回复

登录后才能评论