Problem #30 [Medium]

This problem was asked by Facebook.

You are given an array of non-negative integers that represents a two-dimensional elevation map where each element is unit-width wall and the integer is the height. Suppose it will rain and all spots between two walls get filled up.

Compute how many units of water remain trapped on the map in O(N) time and O(1) space.

For example, given the input [2, 1, 2], we can hold 1 unit of water in the middle.

Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in the second, and 3 in the fourth index (we cannot hold 5 since it would run off to the left), so we can trap 8 units of water.
接雨水问题。对于每一个高度i,我们要找的是它两边的大值的最小值
首先,很容易想到从左到右遍历,从右到左遍历分别找到比当前高度大的值,然后拿到最小值减去当前高度就是可以接到的雨水量。
空间复杂度为O(N), 时间复杂度为O(N), N为height数组的长度。

def trap(height):
        n = len(height)
        pre_max = [-1] *n
        suf_max = [-1] * n
        pre_max[0] = height[0]
        suf_max[-1] = height[-1]
        for i in range(1, n):
            pre_max[i] = max(pre_max[i-1], height[i])
        for i in range(n-2, -1, -1):
            suf_max[i] = max(suf_max[i+1], height[i])
        
        ans = 0
        for h, pre, suf in zip(height, pre_max, suf_max):
             ans += min(pre,suf) - h
        return ans
        

height = [3,0,1,3,0,5]
print(trap(height))

接下来思考如何才能做到O(1)的空间复杂度呢?
那就是单调栈。
单调栈的总结见我的这篇博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值