示例代码

class Solution {
public:
    int trap(vector<int>& height) {
        int res=0;
        int leftMax=0,rightMax=0;
        int left=0,right=height.size()-1;
        while(left<right){
            leftMax=max(leftMax,height[left]);
            rightMax=max(rightMax,height[right]);
            //判断左右两边哪个值比较小,然后再用其对应侧的最大值减去较小的一边的值,就可以得到当前位置存的雨水的高度
            if(height[left]<height[right]){
                res+=leftMax-height[left];
                left++;
            }else{
                res+=rightMax-height[right];
                right--;
            }

        }
        return res;

        


    }
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

效果展示

LeetCode---42. 接雨水(实时更新左右两边最大的值,然后用其对应侧的最大值减去当前左右两边较小的值)_示例代码