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 triprain
if __name__ == '__main__':
s = Solution()
listp = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
res = s.trap_rainwater(listp)
print res