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
分类:
leetcode-单调栈
, leetcode困难题
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)