c++ solution: use two pointer


  • 0
    int trap(vector<int>& height) 
    {
        int left = 0, right = height.size() - 1;
        int area = 0;
        
        while (left < right)
        {
            int hl = height[left];
            int hr = height[right];
            if (height[left] < height[right])
            {
                while (left < right && hl >= height[++left])
                    area += hl - height[left];
            }
            else
            {
                while (right > left && hr >= height[--right])
                    area += hr - height[right];
            }
        }
        
        return area;
    }

Log in to reply
 

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