Loading

[LeetCode] 42. Trapping Rain Water(收集雨水)

Description

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
给定 n 个非负整数表示一个海拔地图,柱状图的单位宽度是 1,计算其在下雨后能收集多少雨水。

Examples

Example 1

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2

Input: height = [4,2,0,3,2,5]
Output: 9

Constraints

  • n == height.length
  • 0 <= n <= 3e4
  • 0 <= height[i] <= 1e5

Solution

这题乍看上去无从下手,实际理解了也不难。我们把关注点转移到每根『柱子』上,只要计算每根『柱子』能收集的雨水量,最后相加即可。大家都知道木桶原理吧,一根『柱子』的储水量取决于其左右两边较矮的那边,所以我们维护左右两边高度的最大值,以此计算每根柱子的储水量。代码如下:

import kotlin.math.max

class Solution {
    fun trap(height: IntArray): Int {
        var left = 0
        var right = height.lastIndex
        var leftMax = 0
        var rightMax = 0
        var result = 0

        while (left <= right) {
            leftMax = max(leftMax, height[left])
            rightMax = max(rightMax, height[right])

            if (leftMax < rightMax) {
                // 先不看右边,至少水不会从右边流走
                result += (leftMax - height[left])
                left++
            } else {
                // 右边同理,水不会从左边流走
                result += (rightMax - height[right])
                right--
            }
        }

        return result
    }
}
posted @ 2020-12-17 09:53  Zhongju.copy()  阅读(70)  评论(0编辑  收藏  举报