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

3sum

时间:2016-05-08 06:45:03      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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)

 

 
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if(num.length<3||num == null)
            return res;
        
        Arrays.sort(num);
        
        for(int i = 0; i <= num.length-3; i++){
            if(i==0||num[i]!=num[i-1]){//remove dupicate
                int low = i+1;
                int high = num.length-1;
                while(low<high){
                    int sum = num[i]+num[low]+num[high];
                    if(sum == 0){
                        ArrayList<Integer> unit = new ArrayList<Integer>();
                        unit.add(num[i]);
                        unit.add(num[low]);
                        unit.add(num[high]);
                        
                        res.add(unit);
                        
                        low++;
                        high--;
                        
                        while(low<high&&num[low]==num[low-1])//remove dupicate
                            low++;
                        while(low<high&&num[high]==num[high+1])//remove dupicate
                            high--;
                            
                    }else if(sum > 0)
                        high --;
                     else
                        low ++;
                }
            }
        }
        return res;
    }
}

 

3sum

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5469695.html

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