前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 题目解析之 4Sum

Leetcode 题目解析之 4Sum

原创
作者头像
ruochen
发布2022-01-08 14:45:34
1.2K0
发布2022-01-08 14:45:34
举报

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);
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档