C++ solution with sort()


  • 1
    S
    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            vector<vector<int>> res;
            // looking for i, j, k
            int len = nums.size();
            for(int i=0; i<len-2; i++)
            {
                if(i>0 && nums[i] == nums[i-1]) continue;
                int j = i+1;
                int k = len-1;
                while(j < k)
                {
                    if(nums[i] + nums[j] == 0 - nums[k])
                    {
                        vector<int> triplet;
                        triplet.push_back(nums[i]);
                        triplet.push_back(nums[j]);
                        triplet.push_back(nums[k]);
                        res.push_back(triplet);
                        while(j<k && nums[j] == nums[++j]);
                    }
                    else if(nums[i] + nums[j] < 0 - nums[k])
                        while(j<k && nums[j] == nums[++j]);
                    else
                        while(k>j && nums[k] == nums[--k]);
                }
            }
            return res;
        }
    };

Log in to reply
 

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