码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][Java] 3Sum

时间:2015-07-09 14:42:02      阅读:129      评论:0      收藏:0      [点我收藏+]

标签: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(n2)。

    从中间搜索周边两个的话需要两层循环。为了避免再次超时,使用仅搜索大于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--;
        }
    }
}


版权声明:本文为博主原创文章,转载注明出处

[LeetCode][Java] 3Sum

标签:leetcode   java   3sum   

原文地址:http://blog.csdn.net/evan123mg/article/details/46814741

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!