42. Trapping Rain Water(Hard)(模拟)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NCUscienceZ/article/details/86994539

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
在这里插入图片描述
Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

记录下当前最大值,然后逐列减去已有高度。

class Solution {
    public int trap(int[] height) {
        int l = 0, r = height.length-1;
        int ans = 0, mymax = 0;
        
        while(l<=r){
            if (height[l] <= height[r]){
                if (height[l] > mymax) mymax = height[l];
                else ans += mymax-height[l];
                l++;
            }else{
                if (height[r] > mymax) mymax = height[r];
                else ans += mymax-height[r];
                r--;
            }
        }
        
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/NCUscienceZ/article/details/86994539