一.問題描述
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.csdn.net/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.csdn.net/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.csdn.net/u014265088/article/details/53241669
@ traverse
@ for similar problem, see https://leetcode.com/problems/container-with-most-water/
@ or maybe for better solution, see http://blog.csdn.net/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]
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)