C++ solution,easy understand


  • 3
    B
    class Solution {
    public:
        int trap(vector<int>& height) {
             if (height.empty()) return 0;
          int h = 0;
          int sum = 0;
          int i =0,j= height.size()-1;
         while(i<j){
             if(height[i]<height[j]){
                 h=max(h,height[i]);
                 sum += h-height[i];
                 i++;
             }
             else{
                 h=max(h,height[j]);
                 sum += h-height[j];
                 j--;
             }
         }
          
          return sum;
        }
    };

Log in to reply
 

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