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)

 

class Solution {
public:
    vector<vector<int>> threeSum(vector<int> &num) 
    {
        vector<vector<int>> ret;
        sort(num.begin(),num.end());
        for(int i=0;i<num.size();i++)
            if(i>0 && num[i]==num[i-1])
                continue;
            else
            {
                int l=i+1;
                int r=num.size()-1;
                while(l<r)
                {
                    if(num[l]+num[r]+num[i]==0)
                    {
                        vector<int> v;
                        v.push_back(num[i]);
                        v.push_back(num[l]);
                        v.push_back(num[r]);
                        ret.push_back(v);
                        
                        l++;while(l<r && num[l]==num[l-1]) l++;
                        r--;while(l<r && num[r]==num[r+1]) r--;
                        continue;
                    }
                    if(num[l]+num[r]+num[i]>0)
                    {
                        r--;continue;
                    }
                    if(num[l]+num[r]+num[i]<0)
                    {
                        l++;continue;
                    }
                }
            }
        return ret;
    }
};
posted @ 2014-05-29 15:29  erictanghu  阅读(119)  评论(0编辑  收藏  举报