LeetCode 015 3Sum

题目描述

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)

分析

求解3个数的和,需要O(n2);去重,需要O(n);

① 对数组进行排序;

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

③ mid指向start+1,q指向结尾。sum = num[start] + num[mid]+ num[end];

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

⑤ 顺带去重。


去重时:

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

② 如果mid++,num[mid] = num[mid - 1],则求出的解肯定重复了。

代码

    public static 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;

            // 相当于2Sum
            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);
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值