LeetCode42.接雨水 JavaScript

給定 n 個非負整數表示每一個寬度爲 1 的柱子的高度圖,計算按此排列的柱子,下雨以後能接多少雨水。

上面是由數組 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種狀況下,能夠接 6 個單位的雨水(藍色部分表示雨水)。 感謝 Marcos 貢獻此圖。javascript

示例:java

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

答案參考:數組

/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function (height) {
    let left = 0, right = height.length - 1
    let count = 0
    let leftMax = 0, rightMax = 0
    while (left <= right) {
        leftMax = Math.max(leftMax, height[left])
        rightMax = Math.max(rightMax, height[right])
        if (leftMax < rightMax) {
            count += leftMax - height[left]
            left++
        } else {
            count += rightMax - height[right]
            right--
        }
    }
    return count
};

歡迎關注

相關文章
相關標籤/搜索