A C++ solution


  • 0
    W
    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) 
        {
            vector<vector<int>> v;        
            sort(nums.begin(), nums.end());;
            for(int i=nums.size()-1; i>1; --i)
            {     
                int k=i-1;
                while(i>0 && i<nums.size()-1 && nums[i] == nums[i+1])
                    --i;
                               
                for(int j=0; j<i; ++j)
                {        
                    for(; k>j && (nums[i] + nums[j] + nums[k]) >= 0; --k)
                    {
                        if(nums[i] + nums[j] + nums[k] == 0 && !(j == k  || k == i))
                        {
                            v.emplace_back();
                            auto &vv=v.back();
                            vv.push_back(nums[i]);
                            vv.push_back(nums[j]);
                            vv.push_back(nums[k]);
                            sort(begin(vv), end(vv));
                        }                  
                    }
                }
            }        
            sort(begin(v), end(v));
            v.erase(unique(begin(v), end(v)), end(v));
            return v;
        }
    };
    

Log in to reply
 

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