Leetcode 42.接雨水

题目描述:

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water

思路:在每一点处雨水的高度 = min(该点左边高度的最大值,该点右边高度的最大值)-当前高度

方法一:遍历数组,找到每一点的左右最大高度值

/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function(height) {
    if(height == null || height.length == 0){
        return 0;
    }
    let n = height.length;
    let left_max = new Array(n);
    let right_max = new Array(n);
    left_max[0] = height[0];
    right_max[n-1] = height[n-1];
    let res = 0;
    for(let i = 1; i < n; i++){
        left_max[i] = Math.max(left_max[i-1], height[i]);
    }
    for(let j = n-2; j >= 0; j--){
        right_max[j] = Math.max(right_max[j+1],height[j]);
        res += Math.min(right_max[j], left_max[j]) - height[j];
    }
    return res;
};

  

原文地址:https://www.cnblogs.com/ZLDJ-15-516/p/11027059.html