essay

hot100-接雨水

#算法

hot100——接雨水

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

示例 1:

image.png

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]

输出:6

解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

示例 2:

输入:height = [4,2,0,3,2,5]

输出:9

提示:

n == height.length

1 <= n <= 2 * 104

0 <= height[i] <= 105

func trap(height []int) int {
    //定义左右挡板,分别用来接往左右两边流的雨水
    leftMax, rightMax := 0, 0
    //左右指针
    left, right := 0, len(height)-1
    result := 0
    for left < right {
        //更新左右挡板
        leftMax = max(leftMax, height[left])
        rightMax = max(rightMax, height[right])
        //右边大,水会往左流
        if height[left] < height[right] {
            //接左边的雨水
            result += leftMax - height[left]
            left++
        } else {
            //接右边的雨水
            result += rightMax - height[right]
            right--
        }
    }
    return result
}
comments如果有不同意见或者补充,直接留在这里。
contact

在别处继续找到我

如果你想聊技术、设计,或者只是打个招呼。

暂未配置外部链接