[LeetCode][Java] 3Sum

题目:

Given an array S of n integers, are there elements abc 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)

题意:

给定一个包含n个整数的数组S,判断数组S中是否存在a,b,c 使得a + b + c = 0? 找出数组中所有和为零的存在且唯一的三元数

注意:

        1.这个三元数中的元素必须是升序的(ie, a ≤ b ≤ c).

        2.找到的所有的三元素,不能出现重复。

    For example, given array S = {-1 0 1 2 -1 -4},

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

算法分析:


参考博客  http://blog.csdn.net/ljiabin/article/details/40620579
               http://www.zhuangjingyang.com/leetcode-3sum/

  • 首先排序所有元素,然后从每个元素开始,检测是否还有两个数字,他们三者相加等于零。这个算法很巧妙。如果我们检测的这三个数字相加大于0了。那么说明大的偏大,所以我们就把上界-1,如果小于0我们就把下界+1,如果相等的话,那么就可以先记录这个值了。那么结果就不可能再同时是另外检测的这两个数字了,所以同时变化。两层循环时间复杂度O(n²)。

    从中间搜索周边两个的话需要两层循环。为了避免再次超时,使用仅搜索大于i的两个数。(一开始不明白为什么,比如说你看-4 -1 -1 0 1 2 中的0如果你从两边搜索分明有两个结果-1 和 1 而只搜索比他大的数字就没有了。这并不矛盾。因为这个结果我们在搜索-1 这个元素的时候就可以搜索到了!)

AC代码:

public class Solution 
{
    List<List<Integer>> ret = new ArrayList<List<Integer>>();
    
    public List<List<Integer>> threeSum(int[] num) 
    {
        if (num == null || num.length < 3) return ret;
        
        Arrays.sort(num);
        
        int len = num.length;
        for (int i = 0; i < len-2; i++) 
        {
            if (i > 0 && num[i] == num[i-1]) continue;//避免结果重复,其后面和它相等的直接被跳过。
            find(num, i+1, len-1, num[i]); //寻找两个数与num[i]的和为0
        }
        
        return ret;
    }
    
    public void find(int[] num, int begin, int end, int target) 
    {
        int l = begin, r = end;
        while (l < r)
        {
            if (num[l] + num[r] + target == 0) 
            {
                List<Integer> ans = new ArrayList<Integer>();
                ans.add(target);
                ans.add(num[l]);
                ans.add(num[r]);
                ret.add(ans); //放入结果集中
                while (l < r && num[l] == num[l+1]) l++;//避免结果重复,其后面和它相等的直接被跳过。
                while (l < r && num[r] == num[r-1]) r--;避免结果重复,其后面和它相等的直接被跳过。
                l++;
                r--;
            } 
            else if (num[l] + num[r] + target < 0) 
                l++;
            else 
                r--;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值