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

15. 三数之和

时间:2019-06-01 11:12:59      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:三元   null   数组   ret   重复   add   integer   不可   内存   

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]]

(1)这道题暴力是O(n^3),肯定感觉肯定会蹦的。
(2)那么可以先固定两个数字,第三个元素可以用二分搜索来查找,这样就把时间复杂度下降到O(nlgn)了,但是我写到最后发现结果:

执行用时 : 186 ms, 在3Sum的Java提交中击败了18.92% 的用户
内存消耗 : 48.6 MB, 在3Sum的Java提交中击败了88.18% 的用户

哭了,直接上代码:

    public Integer binarySearch(int[] a, int begin, int end, int target){
        Integer i = null;

        while(begin <= end){
            if(begin == end){
                if(a[begin] == target){
                    i = a[begin];
                }
                return i;
            }

            int mid = (begin + end) / 2;
            if(a[mid] == target){
                i = a[mid];
                return i;
            }
            if(a[mid] < target){
                begin = mid + 1;
            }else{
                end = mid - 1;
            }
        }
        return i;
    }
    public List<List<Integer>> threeSum(int[] nums){

        List<List<Integer>> endList = new ArrayList<>();
        Integer lasti = null;
        Integer lastj = null;
        Integer lastResult = null;
        Arrays.sort(nums);
        int[] a = nums;
        for(int i = 0; i < a.length-2; i++){
            if(lasti != null && a[i] == lasti){
                continue;
            }
            for(int j= i+1; j < a.length-1; j++){
                if(lastj != null && a[j] == lastj){
                    continue;
                }
                Integer result = binarySearch(a, j+1, a.length-1, -a[i]-a[j]);
                if(result != null){
                    List<Integer> list = new ArrayList<>();
                    list.add(a[i]);
                    list.add(a[j]);
                    list.add(result);
                    endList.add(list);
                }
                lastj = a[j];
            }
            lasti = a[i];
            lastj = null;
        }
        return endList;
    }

15. 三数之和

标签:三元   null   数组   ret   重复   add   integer   不可   内存   

原文地址:https://www.cnblogs.com/disandafeier/p/10958832.html

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