leetcode 18 4Sum JAVA

题目

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

解题思路

将nums数组重新排列,然后从i = 0开始遍历,分别取j = i + 1、left = j + 1和right = nums.length - 1,将nums[i]、nums[j]、nums[left]和nums[right]四数之和与target比较,如果相等则判断结果数组列表中是否存在,存在的话则添加。因为不包含重复的四元组,所以通过一些除重操作减少运行次数。

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length - 3;i++)
        {
            if(i > 0 && nums[i] == nums[i - 1])  //nums[i]与nums[i-1]相同时,则可直接跳过,判断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 left = j + 1;
                int right = nums.length -1;
                while(left < right)
                {                 
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if(sum == target)
                    {
                        List<Integer> temp = new ArrayList<>();
                        temp.add(nums[i]);
                        temp.add(nums[j]);
                        temp.add(nums[left]);
                        temp.add(nums[right]);
                        if(!list.contains(temp))
                            list.add(temp);            
                        right--;
                        left++;
                    }
                    else if(sum > target)
                        right--;
                    else
                        left++;
                }
            }
        }
        return list;
    }
}

  

原文地址:https://www.cnblogs.com/yanhowever/p/10431552.html