leetcode解题笔记-Trapping Rain Water

原题地址:https://oj.leetcode.com/problems/trapping-rain-water/


给一个数组[0,1,0,2,1,0,1,3,2,1,2,1],用直方图表示,向里面灌水,问能灌多少水。

刚开始我的思路就有问题,我计算的是每两个相邻凹槽能灌的水的总量结果错了。

修正后的思路是这样的(参考了网上文章),找出最长的一条,index为i,从0到i之间计算。然后再从右往左,从结尾到i,通过这种方式,我们只需要考虑单方向,简化了问题。代码如下

class Solution:
    # @param A, a list of integers
    # @return an integer
    def trap(self, A):
        if len(A) <= 2:
            return 0
        maxIndex = 0 
        for i in range(0,len(A)):
            if A[maxIndex]<A[i]:
                maxIndex = i
        currentMax = A[0] 
        sum = 0
        for i in range(0,maxIndex+1):
            if currentMax >= A[i]:
                sum += (currentMax - A[i])
            else:
                currentMax = A[i] 
        currentMax = A[len(A)-1]
        for i in range(maxIndex,len(A))[::-1]:
            if currentMax >= A[i]:
                sum += (currentMax - A[i])
            else:
                currentMax = A[i]
        return sum



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值