这里提供一个简单的 Python 代码实现,可以计算出接雨水的总量:

def trap(height):
    if not height:
        return 0

    n = len(height)
    left, right = 0, n-1
    left_max, right_max = height[0], height[n-1]
    res = 0

    while left <= right:
        left_max = max(left_max, height[left])
        right_max = max(right_max, height[right])

        if left_max < right_max:
            res += left_max - height[left]
            left += 1
        else:
            res += right_max - height[right]
            right -= 1

    return res

这个算法的时间复杂度为 $O(n)$,空间复杂度为 $O(1)$。

Python 接雨水算法:高效计算雨水总量