My easy understanding cpp code


  • 0
    C
    class Solution {
    public:
        int skip(const vector<int>& nums, int start, int end)
        {
            int tmp = nums[start];
            while(start <= end && nums[start] == tmp)
                start++;
            return start;
        }
        
        int rskip(const vector<int>& nums, int start, int end)
        {
            int tmp = nums[end];
            while(end >= start && nums[end] == tmp)
                end--;
            return end;
        }
        
        vector<vector<int>> threeSum(vector<int>& nums) 
        {
            vector< vector<int> > res;
            if(nums.size() < 3) return res;
            
            std::sort(nums.begin(), nums.end());
            
            int i = 0;
            while(i <= nums.size()-3)
            {
                int a = nums[i];
                
                int start = i+1, end = nums.size()-1;
                while(start < end)
                {
                    int b = nums[start], c = nums[end];
                    if(a+b+c == 0)
                    {
                        res.push_back(vector<int>{a, b, c});
                        end = rskip(nums, start, end);
                    }
                    else if(a+b+c < 0) start = skip(nums, start, end);
                    else               end = rskip(nums, start, end);
                }
                
                i = skip(nums, i, nums.size()-1);
            }
            
            return res;
        }
    };

Log in to reply
 

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