LeetCode--Trapping Rain Water(捕获雨水)Python

题目:

假设n个非负整数代表一个海拔图,每个条的宽度为1,计算它能在雨后捕获多少水。

For example,

例如,

,

Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

给定数组[ 0,1,0,2,1,0,1,3,2,1,2,1 ],海拔图如下,返回6。

解题思路:

观察该海拔图可以发现被水填满后的形状是先升后降的塔形,因此,先遍历一遍找到塔顶,然后分别从两边开始,往塔顶所在位置遍历,水位只会增高不会减小,且一直和最近遇到的最大高度持平,这样就可以知道当前遍历到的位置的水位为多少,故而再遍历一遍求和即可得到最终的储水量。

代码(Python):

class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        max_h = 0
        index_max = 0
        n = len(height)
        
        for i in range(n):
            if height[i]>max_h:
                max_h = height[i]
                index_max = i
        
        temp_h = 0
        output = 0
        for i in range(index_max):
            if temp_h<height[i]:
                temp_h = height[i]
                continue
            output = output+temp_h-height[i]
            
        temp_h = 0        
        for i in range(n-index_max-1):
            if temp_h<height[-i-1]:
                temp_h = height[-i-1]
                continue
            output = output+temp_h-height[-i-1]
            
        return output

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值