跳到主要内容

资源 · 指南或文章

Rain Terraces (Trapping Rain Water) Problem

逐步讲解接雨水问题:根据每根柱子左右两侧的最高柱子,计算其上方能存住的水量。非常适合数组和动态规划类面试准备。

审核日期

打开原站: Rain Terraces (Trapping Rain Water) Problem (在新标签页中打开原网站)

添加到路线图

把这个资源放进你正在跟进的路线图。它会作为你自己的补充资源显示;路线图的步骤不会改变,也不计入你已记录的步骤。

来源内容语言:英语

Given an array of non-negative integers representing terraces in an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. An element of array can store water if there are higher bars on left and right. We can find amount of water to be stored in every element by finding the heights of bars on left and right sides. The idea is to compute amount of water that can be stored in every element of array. For example, consider the array [3, 0, 0, 2, 0, 4], We can trap "3*2 units" of water between 3 an 2, "1 unit" on top of bar 2 and "3 units" between 2 and 4. See below diagram also. For each element in the array, we find the maximum level of water it can trap after the rain, which is equal to the minimum of maximum height of bars on both the sides minus its own height.

PrepKit 概览

本概览由 PrepKit 编辑根据源代码仓库撰写并审核,并非资源本身的文字。

适合人群
来源未说明适用级别
形式
课程

涵盖内容

  • 三个示例,附 ASCII 图示,输出分别为 2、10 和 6
  • 暴力法:对每根柱子向左右扫描,时间 O(n^2),额外空间 O(1)
  • 动态规划版本:预先计算 left_max 和 right_max 数组,时间 O(n),额外空间 O(n)
  • 给出每根柱子的公式:两侧最大值中的较小者减去柱子高度

使用建议

这是 PrepKit 的学习建议,并非来源的说法。

在方格纸上画出示例 3 并填上水,然后编写动态规划版本,检查结果是否为 6。作为进阶,找出一种 O(1) 空间的方法;页面没有涉及。

范围与局限

止步于动态规划方法,没有双指针解法。部分插图是 GeeksForGeeks 和 LeetCode 的图片。

获取方式与形式

GitHub 上 trekhleb/javascript-algorithms(MIT)中的 README。英文,免费。

PrepKit 于 2026年10月2日 审核。 资源来源提交: 85293e3e2b88

本概览的依据
  • src/algorithms/uncategorized/rain-terraces/README.md

收录此条目的页面

订阅 PrepKit 通讯

可选。使用 PrepKit 并不需要订阅。

我们如何处理你的邮箱