simple easy solution in c++


  • 0
    A
    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            vector<vector<int>>ans;
            if(nums.size()==0)
                return ans;
            sort(nums.begin(), nums.end());
            int n = nums.size();
            int i = 0;
            while(i<=n-3)
            {
                int j = i+1;
                int k = n-1;
                while(j<k)
                {
                    if(nums[i]+nums[j]+nums[k]==0)
                    {
                        vector<int>temp;
                        temp.push_back(nums[i]);
                        temp.push_back(nums[j]);
                        temp.push_back(nums[k]);
                        ans.push_back(temp);
                        while(nums[j]==nums[j+1])
                        j++;
                        while(nums[k]==nums[k-1])
                        k--;
                        j++,k--;
                    }
                    else if((nums[i]+nums[j]+nums[k]>0))
                        k--;
                    else
                        j++;
                }
                while(nums[i]==nums[i+1])
                    i++;
                i++;
            }
            
            return ans;
            
        }
    };
    

Log in to reply
 

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