Clear 56ms C++ solution (sort, use two pointers, avoid duplicates)


  • 0
    N

    class Solution {

    public:

    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> results;
        vector<int> vec(3);
        
        sort(nums.begin(), nums.end());
        
        int len=nums.size();
        for(int i=0; i<len-2; ++i){ //nums[i]+nums[j]+nums[k]=0
            if(i>0 && nums[i]==nums[i-1]) continue; //avoid duplicates
            int j=i+1;
            int k=len-1;
            while(j<k){
                if(nums[i]+nums[j]+nums[k]==0){
                    vec[0]=nums[i];
                    vec[1]=nums[j];
                    vec[2]=nums[k];
                    results.push_back(vec);
                    while(nums[j]==vec[1]) j++; //avoid duplicates
                    while(nums[k]==vec[2]) k--; //avoid duplicates
                }
                else if(nums[i]+nums[j]+nums[k]>0) k--;
                else j++;
            }
        }
        
        return results;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.