首页 > 其他 > 详细

[lintcode medium]3 sum

时间:2015-12-11 06:52:04      阅读:132      评论:0      收藏:0      [点我收藏+]

3Sum

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.

Example

For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:

(-1, 0, 1)
(-1, -1, 2)
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.

 

public class Solution {
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
    public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
        // write your code here
        ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
        
        
        if(numbers==null || numbers.length<3)
        {
            return result;
        }
        
        Arrays.sort(numbers);
        
        for(int i=0;i<numbers.length-2;i++)
        {
            if(i!=0 && numbers[i]==numbers[i-1])
            {
                continue;
            }
            
            int left=i+1;
            int right=numbers.length-1;
            
            while(left<right)
            {
                int sum=numbers[left]+numbers[right]+numbers[i];
                if(sum==0)
                {
                    ArrayList<Integer> list=new ArrayList<Integer>();
                    list.add(numbers[i]);
                    list.add(numbers[left]);
                    list.add(numbers[right]);
                    result.add(list);
                    left++;
                    right--;
                    while(left<right && numbers[left]==numbers[left-1])
                    {
                        left++;
                    }
                    while(left<right && numbers[right]==numbers[right+1])
                    {
                        right--;
                    }
                }
                else if(sum<0)
                {
                    left++;
                }
                else
                {
                    right--;
                }
            }
        }
        return result;
    }
}

 

[lintcode medium]3 sum

原文:http://www.cnblogs.com/kittyamin/p/5037891.html

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