Trapping Rain Water 接雨水 python

来源:互联网 发布:局域网电话软件 编辑:程序博客网 时间:2024/05/12 20:14

 Trapping Rain Water

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.

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


思路分析:

找到最高柱子,从两端逼近,只要是递增不可能存雨水,需要一个peak移动着时刻记录移动中遇到的临时最高的柱子。时间复杂度O(n)

代码如下:

# coding=utf-8"""接雨水"""class Solution(object):    def trap_rainwater(self, listp):        movepeak = 0        triprain = 0        maxindex = 0        for i in range(1, len(listp)):            if listp[i] > listp[maxindex]:                maxindex = i        for i in range(0, maxindex):            if movepeak < listp[i]:                movepeak = listp[i]            else:                triprain += movepeak - listp[i]        movepeak = 0        for j in range(len(listp) - 1, maxindex, -1):            if movepeak < listp[j]:                movepeak = listp[j]            else:                triprain += movepeak - listp[j]        return triprainif __name__ == '__main__':    s = Solution()    listp = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]    res = s.trap_rainwater(listp)    print res


原创粉丝点击