题目描述:
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos贡献此图。
示例:
输入:[0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
#先正序寻找一遍,比当前index对应的柱子 高 的则进行一次接到的雨水计算,同时记录最终的最高柱子下标;再倒序寻找一遍,比当前index对应的柱子 高 的则进行一次接到的雨水计算,同时记录最终的最高柱子下标。最后,若最高柱子下标不同,则说明这两个index中间所对应的雨水量未进行计算
if len(height) <= 2:
return 0
res = 0
#正序寻找一遍:
low = 0
high = 1
while high < len(height)-1:
if height[low] >= height[high]:
high = high + 1
elif height[low] < height[high] and low + 1 == high:
low = high
high = low + 1
else:
for i in range(low,high):
res = res + height[low] - height[i]
low = high
high = low + 1
#记录当前使用到的最后一根柱子
index_1 = low
#倒序寻找一遍:
low = len(height) - 1
high = low - 1
while high > 0:
if height[low] >= height[high]:
high = high - 1
elif height[low] < height[high] and low - 1 == high:
low = high
high = low - 1
else:
for i in range(high+1,low):
res = res + height[low] - height[i]
low = high
high = low - 1
#记录当前使用到的最后一根柱子
index_2 = low
if index_1 != index_2:
for i in range(index_1+1,index_2):
res = res + min(height[index_1],height[index_2]) - height[i]
return res
菜鸟一枚,代码仅供参考,如有问题,望指正~