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)
此題思路有Two Sum而來。二分,注意去重,測試例子如 -2 1 1 1 1 1 檢查。即當左右有重複則雙端指針一直移動。

vector<vector<int> > threeSum(vector<int> &num) 
    {
        if(num.size() < 3) return vector<vector<int> >();
        
        sort(num.begin(),num.end());
        
        vector<int> res_one(3);
        vector<vector<int> > res;
        for(int i = 0;i <= num.size()-3;i++)
        {
            if(i > 0 && num[i] == num[i-1])continue;
            
            int left = i+1;
            int right = num.size() -1 ;
            
            while(left < right)
            {
                if((num[i] + num[left] + num[right] )== 0) 
                {
                    res_one[0] = num[i];
                    res_one[1] = num[left];
                    res_one[2] = num[right];
                    res.push_back(res_one);
                    //之後還要繼續
                    left++;
                    right--;
                    
                    while(left < right&&num[left] == num[left-1])//否則有重複 //防止 000 222 求2的情況
    				left++;
    
    				
    				while(left < right&&num[right] == num[right+1])//否則有重複
    				right--;
				
                }
                else if((num[left] + num[right]) > (-1*num[i]))
                {
                    right--;
                }
                else
                {
                   left++;
                }
            }
        }
        return res;
    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章