3 nums

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.

Note: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> threeSum(vector& nums) {

    }
};

思路:
当初写2 sum时,是从大到小先排序,然后从左右两端向中间找,如果left与right之和比target大,那么right -= 1,反之left += 1,遍历一遍可解。
3 sum的话就第一层选一个数,然后在剩下的用2 sums即可


    class Solution {
public:
    vector> threeSum(vector& nums) {
        vector >  result;    

        sort(nums.begin(), nums.end());    

        /*Call 2 sum*/  
        for(int i = 0; i < nums.size(); i++){    
            if(i > 0 && nums[i] == nums[i-1]) continue;    
            twoSum(nums, result, i);  
        }   
        return result; 
    }
    void twoSum(vector &num, vector> &res, int targetIndex) {  
        /*starting from targetIndex + 1 is because the numbers before have been used*/  
            int i = targetIndex + 1;     
            int j = num.size()-1;    

            while(i < j){    
                if(num[targetIndex] + num[i] + num[j] < 0)   i++;    
                else if(num[targetIndex] + num[i] + num[j] > 0)   j--;    
                else{    
                    vector v;    
                    v.push_back(num[targetIndex]);    
                    v.push_back(num[i]);    
                    v.push_back(num[j]);    
                    res.push_back(v);    
                    i++; j--;    
                    while(i < num.size() && num[i]==num[i - 1]) i++;    
                    while(j >= 0 && num[j] == num[j + 1]) j--;    
                }    
            }  

    }  
};