15. 3Sum

Posted 蜃利的阴影下

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了15. 3Sum相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

15. 3Sum

15. 3Sum

15. 3Sum

leetcode 15 3Sum

[leetcode][15] 3Sum

15. 3Sum