Skip to content

接雨水

仲灏2025-04-02约 1 分钟

<div style="display: none;" hidden="true" aria-hidden="true" data-nosnippet>Are you an LLM? You can read better optimized documentation at /pages/abf247.md for this page in Markdown format</div>

接雨水

CategoryDifficultyLikesDislikes
algorithmsHard (63.24%)5001-

Tags

Companies

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例 1:

img

plain
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

示例 2:

plain
输入:height = [4,2,0,3,2,5]
输出:9

提示:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

Discussion | Solution

代码

javascript
/*
 * @Author: 仲灏<izhaong@outlook.com>🌶🌶🌶
 * @Date: 2024-02-06 12:36:21
 * @LastEditTime: 2024-02-06 13:11:52
 * @LastEditors: 仲灏<izhaong@outlook.com>🌶🌶🌶
 * @Description:
 * @FilePath: /leetcode/42.接雨水.js
 */
/*
 * @lc app=leetcode.cn id=42 lang=javascript
 *
 * [42] 接雨水
 *
 * https://leetcode.cn/problems/trapping-rain-water/description/
 *
 * algorithms
 * Hard (63.24%)
 * Likes:    5001
 * Dislikes: 0
 * Total Accepted:    856.9K
 * Total Submissions: 1.4M
 * Testcase Example:  '[0,1,0,2,1,0,1,3,2,1,2,1]'
 *
 * 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
 *
 *
 *
 * 示例 1:
 *
 *
 *
 *
 * 输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
 * 输出:6
 * 解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
 *
 *
 * 示例 2:
 *
 *
 * 输入:height = [4,2,0,3,2,5]
 * 输出:9
 *
 *
 *
 *
 * 提示:
 *
 *
 * n == height.length
 * 1 <= n <= 2 * 10^4
 * 0 <= height[i] <= 10^5
 *
 *
 */

// @lc code=start
/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function (height) {
    let area = 0
    const stack = []
    for (let i = 0; i < height.length; i++) {
        while (stack.length && height[i] >= height[stack[stack.length - 1]]) {
            const bh = height[stack.pop()]
            if (!stack.length) {
                break;
            }
            const end = stack[stack.length - 1]
            const ca = (Math.min(height[end], height[i]) - bh) * (i - end - 1)
            area += ca
        }
        stack.push(i)
    }
    return area

};
// @lc code=end

// @after-stub-for-debug-begin
module.exports = trap;
// @after-stub-for-debug-end