首页 > 其他 > 详细

[Leetcode] 3Sum

时间:2015-09-30 14:34:04      阅读:129      评论:0      收藏:0      [点我收藏+]

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


  1. sort the array

  2. one out loop for the first element ( careful about the duplicate)

  3. inside the loop, two pointers from two-end to middle

 

edgecase

nums == null ?

nums.length == 0?


Note:

avoid duplicate

 

    public List<List<Integer>> threeSum(int[] nums){
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(nums == null || nums.length == 0) return res;
        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i++){
            if(i>0 && nums[i] == nums[i-1]) continue;
            int j = i+1;
            int k = nums.length-1;
            while(j<k){
                int sum = nums[i] + nums[j] + nums[k];
                if(sum == 0){
                    List<Integer> one = new ArrayList<Integer>();
                    one.add(nums[i]);
                    one.add(nums[j]);
                    one.add(nums[k]);
                    res.add(one);
                    while(j <k && nums[j] == nums[j+1]){
                        j++;
                    }
                    j++;
                    while(j<k && nums[k] == nums[k-1]){
                        k--;
                    }
                    k--;
                }
                else if(sum > 0){
                    k--;
                }
                else{
                    j++;
                }
            }
    
        }
        return res;

    }

 

[Leetcode] 3Sum

原文:http://www.cnblogs.com/momoco/p/4849062.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!