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

Leetcode 题目解析之 3Sum

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

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

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.``` For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2) ```分析:

对数组进行排序;

start从0到n-1,对numstart求另外两个数,这里用mid和end;

mid指向start+1,q指向结尾。sum = numstart + nummid+ numend;

利用加逼定理求解,终止条件是mid == end;

顺带去重

去重:

如果start到了start+1,numstart == numstart - 1,则求出的解肯定重复了;

如果mid++,nummid = nummid - 1,则求出的解肯定重复了。

代码语言:txt
复制
    public List<List<Integer>> threeSum(int[] nums) {
        if (nums == null || nums.length < 3) {
            return new ArrayList<List<Integer>>();
        }
        Set<List<Integer>> set = new HashSet<List<Integer>>();
        Arrays.sort(nums);
        for (int start = 0; start < nums.length; start++) {
            if (start != 0 && nums[start - 1] == nums[start]) {
                continue;
            }
            int mid = start + 1, end = nums.length - 1;
            while (mid < end) {
                int sum = nums[start] + nums[mid] + nums[end];
                if (sum == 0) {
                    List<Integer> tmp = new ArrayList<Integer>();
                    tmp.add(nums[start]);
                    tmp.add(nums[mid]);
                    tmp.add(nums[end]);
                    set.add(tmp);
                    while (++mid < end && nums[mid - 1] == nums[mid])
                        ;
                    while (--end > mid && nums[end + 1] == nums[end])
                        ;
                }
                else if (sum < 0) {
                    mid++;
                }
                else {
                    end--;
                }
            }
        }
        return new ArrayList<List<Integer>>(set);
    }

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

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

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

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

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