接雨水:双指针法

  以列表的形式给定 n n n个非负整数表示每个宽度为 1 1 1的柱子的高度图,列表的索引表示对应柱子左边界所处坐标。计算按此排列的柱子,下雨之后能接多少雨水。如: [ 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 ] [0,1,0,2,1,0,1,3,2,1,2,1] [0,1,0,2,1,0,1,3,2,1,2,1]可以接 6 6 6个单位的雨水。
  容易想到双指针法,关键在于确定跟新指针的法则。
  水最多可以装多高由左侧与右侧柱子中的较长者决定,因此每次更新时固定指向较长柱的指针;具体可以装多少水由当前较短柱侧当最高柱与较短柱的落差决定,因此需要记录当前的最高柱,并根据落差更新结果。

def trap(height):
    l_index, r_index = 0, len(height) - 1
    l_max, r_max = 0, 0
    result = 0
    while l_index < r_index:
        if height[l_index] < height[r_index]:
            if height[l_index] >= l_max:
                l_max = height[l_index]
            else:
                result += l_max - height[l_index]
            l_index += 1
        else:
            if height[r_index] >= r_max:
                r_max = height[r_index]
            else:
                result += r_max - height[r_index]
            r_index -= 1

    return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值