LeetCode42 接雨水(单调栈)

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   

posted on 2022-06-30 10:51  solvit  阅读(39)  评论(0编辑  收藏  举报

导航