Skip to content

42. 接雨水 ​

  • 题号:42
  • 来源:LeetCode
  • 难度:困难
  • 标签:数组 双指针
  • 语言:TypeScript · Python
  • 解法:2 个
  • 作者:lmliheng
  • 最近更新:2026-09-29

TypeScript ​

TypeScript · O(n) 时间 · O(1) 空间 · 更新于 2026-09-27

以最高柱为中轴,两侧累加前缀最大值差

typescript
/**
 * @difficulty hard
 * @tags 数组,双指针
 * @time O(n)
 * @space O(1)
 * @note 以最高柱为中轴,两侧累加前缀最大值差
 * @42. 接雨水
 */
/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function (height: number[]) {
    let maxHeightIndex = height.indexOf(Math.max(...height))
    let maxArea = 0
    let leftmaxHeight = 0
    let rightmaxHeight = 0
    for (let i = 0; i < maxHeightIndex; i++) {
        if (height[i] > leftmaxHeight) {
            leftmaxHeight = height[i]
        }
        maxArea += leftmaxHeight - height[i]
    }
    for (let i = height.length - 1; i > maxHeightIndex; i--) {
        if (height[i] > rightmaxHeight) {
            rightmaxHeight = height[i]
        }
        maxArea += rightmaxHeight - height[i]
    }
    return maxArea

};

源码:ts/leetcode/42. 接雨水.ts

Python ​

Python · O(n) 时间 · O(1) 空间 · 更新于 2026-09-29

按最高点把数组分成左右两段,各自维护本侧最大值累加差值

python
"""
@lc 42
@title 接雨水
@difficulty hard
@tags 数组,双指针
@time O(n)
@space O(1)
@note 按最高点把数组分成左右两段,各自维护本侧最大值累加差值
"""

class Solution:
    def trap(self, height: List[int]) -> int:
        res=0
        max_height = max(height)
        max_height_index = height.index(max_height)
        left_max_height=0
        right_max_height=0
        for i in range(max_height_index+1):
            if height[i]>left_max_height:
                left_max_height=height[i]
            else:
                res+=left_max_height-height[i]

        for i in range(len(height)-1, max_height_index-1 , -1):
            if height[i]>right_max_height:
                right_max_height=height[i]
            else:
                res+=right_max_height-height[i]

        return res

源码:python/leetcode/hot100/7.py


在 GitHub 上查看题目所在目录:lmliheng/algorithm