一.问题描述
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
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
二.代码编写
第一轮循环从左至右找到每一个位置左边的最大值存入list_flag;
第二轮循环从右至左找到每一个位置右边的最大值,若该值比list_flag[i]小,则替换list_flag[i]
第三轮循环如果当前list_flag[i]大于height[i],则sum=sum+list_flag[i]-height[i]。【list_flag[i]-height[i]为当前位置可储水量】。
很明显时间复杂度和空间复杂度都是O(N)。
实现代码如下:
'''
@ 2016.11.20 by wttttt
@ for problem detail, see https://leetcode.com/problems/trapping-rain-water/
@ for solution detail, see http://blog.youkuaiyun.com/u014265088/article/details/53241669
@tarverse
@ for similar problem, see https://leetcode.com/problems/container-with-most-water/
@ or maybe for better solution, see http://blog.youkuaiyun.com/u014265088/article/details/52575323
'''
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
len_hei = len(height)
list_flag = [0 for i in range(len_hei)]
max_v = 0
for i in range(len_hei):
list_flag[i] = max_v
if height[i]>max_v:
max_v = height[i]
print list_flag
max_right = 0
for i in range(len_hei-1,-1,-1):
if max_right<list_flag[i]:
list_flag[i] = max_right
if height[i]>max_right:
max_right = height[i]
print list_flag
sum = 0
for i in range(len_hei):
if list_flag[i]>height[i]:
sum = sum+list_flag[i]-height[i]
return sum
so = Solution()
height = [4,2,3]
print so.trap(height)
三.代码改进
提交之后发现效率不太好,再看代码发现第三遍循环完全可以合并到第二遍里面呀,这样就减少一次循环,效率还是有很好的提高的,代码:
''' @ 2016.11.20 by wttttt @ for problem detail, see https://leetcode.com/problems/trapping-rain-water/ @ for solution detail, see http://blog.youkuaiyun.com/u014265088/article/details/53241669
class Solution(object):@ traverse @ for similar problem, see https://leetcode.com/problems/container-with-most-water/ @ or maybe for better solution, see http://blog.youkuaiyun.com/u014265088/article/details/52575323 '''
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
len_hei = len(height)
list_flag = [0 for i in range(len_hei)]
max_v = 0
for i in range(len_hei):
list_flag[i] = max_v
if height[i]>max_v:
max_v = height[i]
sum = 0
max_right = 0
for i in range(len_hei-1,-1,-1):
vv = min(max_right, list_flag[i])
if vv > height[i]:
sum = sum+vv-height[i]
#if max_right<list_flag[i]:
#list_flag[i] = max_right
if height[i]>max_right:
max_right = height[i]
#for i in range(len_hei):
#if list_flag[i]>height[i]:
#sum = sum+list_flag[i]-height[i]
return sum
so = Solution()
height = [4,2,3]
print so.trap(height)