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
假设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
相关文章推荐
- Leetcode刷题记——Trapping Rain Water(捕获雨水)
- [LeetCode] Trapping Rain Water 收集雨水
- [LeetCode] Trapping Rain Water II 收集雨水之二
- Trapping Rain Water(捕获雨水)
- [LeetCode]题解(python):042-Trapping Rain Water
- [LeetCode] Trapping Rain Water 搜集雨水
- Leetcode 407. Trapping Rain Water II 收集雨水2 解题报告
- LeetCode Trapping Rain Water等雨水的凹槽容量
- LeetCode:Trapping Rain Water(装雨水问题)
- [LeetCode] Trapping Rain Water 三种方案 Python
- Trapping Rain Water 接雨水 python
- [LeetCode] 407. Trapping Rain Water II 收集雨水 II
- leetcode 【 Trapping Rain Water 】python 实现
- [Leetcode][python]Trapping Rain Water
- LeetCode 接雨水 Trapping Rain Water 积水问题
- Leetcode_trapping-rain-water(updated c++ and python version)
- LeetCode - Trapping Rain Water 等雨水的凹槽容量
- Trapping Rain Water 捕获最多的雨水
- [leetcode]Trapping Rain Water @ Python
- Trapping Rain Water -- LeetCode