LeetCode 题解工作台

接雨水

给定 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] 表示的高度图,在这种情况…

category

5

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

困难 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示下标 位置及其左边的最高柱子的高度,定义 表示下标 位置及其右边的最高柱子的高度。那么下标 位置能接的雨水量为 $\min(left[i], right[i]) - height[i]$。我们遍历数组,计算出 和 ,最后答案为 $\sum_{i=0}^{n-1} \min(left[i], right[i]) - height[i]$。 时间复杂度 ,空间复杂度 。其中 …

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定 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 * 104
  • 0 <= height[i] <= 105
lightbulb

解题思路

方法一:动态规划

我们定义 left[i]left[i] 表示下标 ii 位置及其左边的最高柱子的高度,定义 right[i]right[i] 表示下标 ii 位置及其右边的最高柱子的高度。那么下标 ii 位置能接的雨水量为 min(left[i],right[i])height[i]\min(left[i], right[i]) - height[i]。我们遍历数组,计算出 left[i]left[i]right[i]right[i],最后答案为 i=0n1min(left[i],right[i])height[i]\sum_{i=0}^{n-1} \min(left[i], right[i]) - height[i]

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组的长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def trap(self, height: List[int]) -> int:
        n = len(height)
        left = [height[0]] * n
        right = [height[-1]] * n
        for i in range(1, n):
            left[i] = max(left[i - 1], height[i])
            right[n - i - 1] = max(right[n - i], height[n - i - 1])
        return sum(min(l, r) - h for l, r, h in zip(left, right, height))
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you understand why precomputing left and right max heights ensures correct trapped water calculation?

  • question_mark

    Can you explain how two-pointer traversal reduces space usage while maintaining accurate state transitions?

  • question_mark

    Will you handle edge cases where consecutive bars are equal or the array has a single peak?

warning

常见陷阱

外企场景
  • error

    Failing to update left_max or right_max properly, causing underestimation of trapped water in valleys.

  • error

    Confusing index distances when using the stack approach, leading to overcounting trapped units.

  • error

    Assuming all dips trap water without considering the bounding higher bars, which results in incorrect totals.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute trapped water when elevation map elements are floating-point heights instead of integers.

  • arrow_right_alt

    Calculate trapped water using only constant extra space without modifying the original array.

  • arrow_right_alt

    Determine the maximum single valley water accumulation instead of total trapped water.

help

常见问题

外企场景

接雨水题解:状态·转移·动态规划 | LeetCode #42 困难