Leetcode 题目解析之 4Sum

2022-01-08 14:45:34 浏览数 (2)

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)

代码语言:txt复制
    public 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 a = 0; a < nums.length - 3; a  ) {
            int target_3Sum = target - nums[a];
            for (int b = a   1; b < nums.length - 2; b  ) {
                int c = b   1, d = nums.length - 1;
                while (c < d) {
                    int sum = nums[b]   nums[c]   nums[d];
                    if (sum == target_3Sum) {
                        // 将结果加入集合
                        List<Integer> tmp = new ArrayList<Integer>();
                        tmp.add(nums[a]);
                        tmp.add(nums[b]);
                        tmp.add(nums[c]);
                        tmp.add(nums[d]);
                        set.add(tmp);
                        // 去重
                        while (  c < d && nums[c - 1] == nums[c])
                            ;
                        while (--d > c && nums[d   1] == nums[d])
                            ;
                    }
                    else if (sum < target_3Sum) {
                        c  ;
                    } else {
                        d--;
                    }
                }
            }
        }
        return new ArrayList<List<Integer>>(set);
    }

0 人点赞