您的位置:首页 > 移动开发

LeetCode--Trapping Rain Water(捕获雨水)Python

2017-11-27 11:30 1211 查看
题目:

假设n个非负整数代表一个海拔图,每个条的宽度为1,计算它能在雨后捕获多少水。

For example,
例如,
lì例
rú如
,

Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
给定数组[ 0,1,0,2,1,0,1,3,2,1,2,1 ],海拔图如下,返回6。

解题思路:
观察该海拔图可以发现被水填满后的形状是先升后降的塔形,因此,先遍历一遍找到塔顶,然后分别从两边开始,往塔顶所在位置遍历,水位只会增高不会减小,且一直和最近遇到的最大高度持平,这样就可以知道当前遍历到的位置的水位为多少,故而再遍历一遍求和即可得到最终的储水量。
代码(Python):
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_h = 0
index_max = 0
n = len(height)

for i in range(n):
if height[i]>max_h:
max_h = height[i]
index_max = i

temp_h = 0
output = 0
for i in range(index_max):
if temp_h<height[i]:
temp_h = height[i]
continue
output = output+temp_h-height[i]

temp_h = 0
for i in range(n-index_max-1):
if temp_h<height[-i-1]:
temp_h = height[-i-1]
continue
output = output+temp_h-height[-i-1]

return output
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: