[leetcode]042-Trapping Rain Water[数理逻辑]

1. 原题

https://leetcode.com/problems/trapping-rain-water/

2. 思路

题意,求出柱体间能够容纳的水面积。

考查逻辑能力。我们找到一个居中的最大值,

然后从两边向中间遍历累加值即可。

3. 源码

# find the max value of center, then collect water from side to center
class Solution:
    def trap(self, height: List[int]) -> int:
        if len(height) < 2:
            return 0
        mv, mv_id = -1, -1 #max value and its index
        for i, val in enumerate(height):
            if val >mv:
                mv = val
                mv_id = i
                
        last , area= height[0], 0
        for i in range(1, mv_id):
            if height[i] > last: # here we cannot collect water
                last = height[i]
            else:
                area += last-height[i]
        last= height[len(height)-1]
        for i in range(len(height)-1, mv_id, -1):
            if height[i] > last:
                last = height[i]
            else:
                area += last-height[i]
        return area

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值