42. 接雨水

发布时间 2023-10-27 18:43:38作者: BJFU-VTH

链接

https://leetcode.cn/problems/trapping-rain-water/description/

思路

1. 在线处理。既然是接雨水,那肯定是形成一个类似于碗的结构才能接。可以先找到一个最大值当兜底,然后不断的用当前border去夹逼。如果遇到比当前border高的,那应该更新border。

2. 单调栈。跟在线处理思路类似,但又不同。单调栈解法可以想象成雨水是从天而降,一层一层的往上铺。

代码一

class Solution:
    def trap(self, height: List[int]) -> int:
        max_height = max(height)
        max_idx = height.index(max_height)
        min_height = height[0]
        res = 0
        for i in range(max_idx):
            if height[i] <= min_height:
                res += min_height-height[i]
            else:
                min_height = height[i]
        min_height = height[-1]
        for i in range(len(height)-1, max_idx, -1):
            if height[i] <= min_height:
                res += min_height-height[i]
            else:
                min_height = height[i]
        return res

 

代码二

class Solution(object):
    def trap(self, height):
        single_stack = []
        res = 0
        for i in range(len(height)):
            right_border_idx = i
            while single_stack and height[single_stack[-1]] < height[i]:
                bottom_idx = single_stack.pop()
                bottom_val = height[bottom_idx]
                while single_stack and bottom_val == height[single_stack[-1]]:
                    single_stack.pop()
                if single_stack:
                    left_border_idx = single_stack[-1]
                    left_border_val = height[left_border_idx]
                    res += (min(left_border_val, height[i])-bottom_val) * (right_border_idx-left_border_idx-1)
            single_stack.append(right_border_idx)
        return res