class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
cache = [] #保存凸出来的柱子
area = 0
if len(height) < 3: #只有两个或者以下的柱子不能存水
return 0
for index in range(0, len(height)):
if index == 0:
if height[0] > height[1]:
cache.append(0)
elif index <len(height) - 1:
if height[index] >= height[index - 1] and height[index] >= height[index + 1] and height[index] * 2 != height[index - 1] + height[index + 1]:
cache.append(index)
else:
if height[index] > height[index - 1]:
cache.append(index)
def simplify(content): #两个较高的柱子之间,较低的凸台并不能限制存水量
if len(content) <= 2:
return content
else:
left = height[content[0]] #左端点高度
right = height[content[-1]] #右端点高度
less = min(left, right)
temp = [element for element in content if height[element] >= less] #小于较低柱子没有起到限制作用
if less == left:
ret = []
ret.append(temp[0])
ret.extend(simplify(temp[1:])) #如果左边较低,那么中间较高柱子与右端柱子重复该过程
else:
ret = []
ret.append(temp[-1])
ret = simplify(temp[0:-1]) + ret
return ret
cache = simplify(cache)
for i in range(len(cache) - 1):
left = cache[i]
right = cache[i + 1]
limit = min(height[left], height[right])
for i in range(left+1, right):
if height[i] < limit:
area += limit - height[i]
return area
#end def
height = [6,4,2,0,3,2,0,3,1,4,5,3,2,7,5,3,0,1,2,1,3,4,6,8,1,3]
a = Solution().trap(height)
print(a)
LeetCode 42. Trapping Rain Water (python)
最新推荐文章于 2020-07-15 12:29:08 发布