Skip to content

接雨水

设置前后两个指针left、right,分别表示当前Height数组的遍历程度。

leftMax、rightMax分别表示left、right指针遍历过的最大值。

如果leftMax < rightMax,则说明,leftMax是其中较小的那个。 所以计算方式是 leftMax - height[left]

某格能接的雨水量,取决于它作用两边最高的柱子中,更矮的那个。

js
/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function(height) {
    
    let len = height.length;
    let right = len - 1;
    let left = 0;

    let rightMax = height[right];
    let leftMax = height[left];

    let count = 0;

    while(left < right){
        rightMax = Math.max(rightMax, height[right]);
        leftMax = Math.max(leftMax, height[left]);
        // 蓄水量只取决于短板
        // 通过left和right双指针来高效计算。
        if(height[left]<height[right]){
            count += leftMax - height[left];
            left++;
        }else{
            count += rightMax - height[right];
            right--;
        }
    }
    return count;
};
本站访客数 人次 本站总访问量