LeetCode 018 4Sum

题目描述

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

A solution set is:
(-1,  0, 0, 1)
(-2, -1, 1, 2)
(-2,  0, 0, 2)

代码

    public static List<List<Integer>> fourSum(int[] nums, int target) {

        if (nums == null || nums.length < 4) {
            return new ArrayList<List<Integer>>();
        }

        Arrays.sort(nums);

        Set<List<Integer>> set = new HashSet<List<Integer>>();

        // 和3Sum一样,只不过多了一个循环
        for (int first = 0; first < nums.length - 3; first++) {

            int target_3Sum = target - nums[first];

            for (int second = first + 1; second < nums.length - 2; second++) {

                int third = second + 1, fourth = nums.length - 1;

                while (third < fourth) {

                    int sum = nums[second] + nums[third] + nums[fourth];

                    if (sum == target_3Sum) {
                        List<Integer> tmp = new ArrayList<Integer>();
                        tmp.add(nums[first]);
                        tmp.add(nums[second]);
                        tmp.add(nums[third]);
                        tmp.add(nums[fourth]);
                        set.add(tmp);

                        while (++third < fourth
                                && nums[third - 1] == nums[third])
                            ;
                        while (--fourth > third
                                && nums[fourth + 1] == nums[fourth])
                            ;
                    }

                    else if (sum < target_3Sum) {
                        third++;
                    } else {
                        fourth--;
                    }
                }
            }
        }

        return new ArrayList<List<Integer>>(set);
    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/49633137
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞