150强访谈简单

收集雨水

“捕获雨水”问题的详细指南和 Python 实施。

问题陈述

简单

给定 n 非负整数表示海拔图,其中每个条形的宽度为 1,计算下雨后它可以捕获多少水。

编写一个函数 trap(height: List[int]) -> int

约束条件
  • n == len(height)
  • 1 <= n <= 2 * 10^4
  • 0 <= height[i] <= 10^5

示例

Example 1
Input
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output
6
Explanation

The elevation map traps 6 units of rain water. Water fills between the bars: 1 unit above index 2, 1 unit above index 4, 2 units above index 5, 1 unit above index 6, and 1 unit above index 9.

Example 2
Input
height = [4, 2, 0, 3, 2, 5]
Output
9
Explanation

Water trapped: 2 above index 1, 4 above index 2, 1 above index 3, 2 above index 4 = 9 total.

Need a Hint?
考虑使用特定于两指针的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。