LeetCode42 接雨水(单调栈)
作者:互联网
维护一个单调栈,单调栈存储的是下标,满足从栈底到栈顶的下标对应的数组 height 中的元素递减
每次遇到大于栈顶元素的值时进行答案累计
class Solution:
def trap(self, height: List[int]) -> int:
ans, stack, l = 0, [], len(height)
for i in range(l):
while stack and height[stack[-1]] < height[i]:
top = stack.pop()
if not stack: break
width = i - stack[-1] - 1
lenght = min(height[i], height[stack[-1]]) - height[top]
ans += (width * lenght)
stack.append(i)
return ans
标签:int,lenght,雨水,height,ans,LeetCode42,stack,单调 来源: https://www.cnblogs.com/solvit/p/16426051.html