[LeetCode]3Sum

来源:互联网 发布:java论坛网站建设 编辑:程序博客网 时间:2024/04/25 07:56
题意: 找出一个数组内和为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;    }


0 0
原创粉丝点击