42.接雨水

2020/10/1

必须左右都有比它高的柱子
分别取出左右最高的柱子(且比自身高),比较左右大小,小的减去自身高度便是雨水高度

class Solution {
    public int trap(int[] height) {
        int sum = 0;
        int length = height.length;
        for(int i=1; i<length-1; i++){
            int L = i-1;
            int R = i+1;
            int left = 0;
            int right = 0;
            while(L>=0){
                if(height[L]>height[i] && height[L]>left){
                    left = height[L];
                }
                L--;
            }
            while(R<=length-1){
                if(height[R]>height[i] && height[R]>right){
                    right = height[R];
                }
                R++;
            }
            int temp = left<right?left:right;
            if(temp>0){
                temp = temp - height[i]; //左右分别有比自身高的柱子,则取左右两数的最小值并减去自身高度
            }
            sum = sum + temp;
        }
        return sum;
    }
}
Last Updated: 4/4/2024