码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]3Sum

时间:2015-04-01 20:05:40      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题意: 找出一个数组内和为0的三元组,元组不能重复
思路1:.直接暴力DFS,这样会超时,不过先排序加上剪枝的花据说能够AC
思路2:先排序O(N*log(N)),然后遍历a 从0 到 nums.length - 2, 结下来的问题就简化为2Sum的问题了 复杂度O(N*N)
代码:

    public List<List<Integer>> threeSum(int[] num) {
        List<List<Integer>> rs = new LinkedList<List<Integer>>();
        if(num == null || num.length < 3) return rs;//不能返回null
        Arrays.sort(num);
        System.out.println();
        //a + b + c ==0
        final int target = 0;
        for(int a =0; a < num.length-2;){//先固定第一个数字
            if(num[a] > target) return rs;
            int b = a + 1, c = num.length - 1;
            while (b < c){//对后面两个数据进行调整
                int sum = num[a] + num[b] + num[c];
                if(sum == target){
                    List<Integer> r = new LinkedList<Integer>();
                    r.add(num[a]);
                    r.add(num[b]);
                    r.add(num[c]);
                    rs.add(r);
                    b++;
                    while (b<c && num[b] == num[b-1])b++;//防止重复数据
                    c--;
                    while (b<c && num[c + 1] == num[c])c--;

                }else if(sum > target){
                    c--;
                }else {
                    b++;
                }
            }
            a ++;
            while (a< num.length -2 && num[a-1] == num[a]) a++;//防止重复
        }
        return rs;
    }


[LeetCode]3Sum

标签:leetcode

原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/44810745

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