首页 > 其他 > 详细

15. 3Sum

时间:2016-03-11 01:08:47      阅读:133      评论: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)

 

Subscribe to see which companies asked this question

Hide Tags
 Array Two Pointers
 
 
public class Solution {
    public List<List<Integer>> threeSum(int[] num) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(num == null || num.length<3)
            return result;
        
        Arrays.sort(num);
        for(int first = 0;first<num.length-2;++first)
        {
            if(first > 0 && num[first]==num[first-1])
                continue;
            if(num[first]>0)
                break;
            
            int second = first+1;
            int third = num.length -1;
            
            while(second<third)
            {
                int sum = num[first]+num[second]+num[third]; 
                if(sum == 0)
                {
                    List<Integer> l = new ArrayList<Integer>();
                    l.add(num[first]);
                    l.add(num[second]);
                    l.add(num[third]);
                    result.add(l);
                    while(++second<third && num[second]==num[second-1]);
                    while(second<--third && num[third]==num[third+1]);
                }
                else if(sum>0)
                    while(second<--third && num[third]==num[third+1]);
                else 
                    while(++second<third && num[second]==num[second-1]);
            }
            
        }
        
        return result;
    }
}

 

 

 

15. 3Sum

原文:http://www.cnblogs.com/neweracoding/p/5264095.html

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