42. Trapping Rain Water(python) 解题记录

  1. Trapping Rain Water(python)
    Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
    在这里插入图片描述
    The above elevation map 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. Thanks Marcos for contributing this image!

这个题和11. Container With Most Water是相似的,主要思路是给两个指针,while语句从两边向中间遍历。在遍历时同时求所有的影音面积和数列的和,然后用所有的阴影面积减去数列的和既是乘的水。

    def trap(self, height: List[int]) -> int:
        i=0
        j=len(height)-1
        sum1=0
        sum2=0
        min_num=0
        while i<=j:            
            if height[i]<height[j]: 
                sum1+=height[i]
                if height[i]>min_num: 
                    sum2+=(height[i]-min_num)*(j-i+1)
                    min_num=height[i]
                else:
                    pass
                i+=1
            else:
                sum1+=height[j]
                if height[j]>min_num:
                    sum2+=(height[j]-min_num)*(j-i+1)  
                    min_num=height[j]
                else:
                    pass
                j-=1
        return sum2-sum1

代码形式有点罗嗦,不过好在清楚详细,也不影响效率。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值