42. 接雨水

链接

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

 2024刷

class Solution(object):
    def trap(self, height):
        single_stack = []
        res = 0
        for i in range(len(height)):
            right_border_idx = i
            right_border_val = height[right_border_idx]
            while single_stack and height[single_stack[-1]] < height[right_border_idx]:
                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, right_border_val) - bottom_val) * (right_border_idx-left_border_idx-1)
            single_stack.append(right_border_idx)
        return res

 

posted @ 2023-10-27 18:39  BJFU-VTH  阅读(31)  评论(0编辑  收藏  举报