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 @   BJFU-VTH  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示