Trapping Rain Water

文章介绍了如何使用两指针方法解决在给定海拔地图上计算降雨后每个位置被困水体积的问题,通过遍历地图并动态更新左右边界的最大高度来实现,时间复杂度为O(n),空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Intuition

The problem involves calculating the amount of water that can be trapped between the bars of an elevation map after raining. The idea is to use a two-pointer approach to determine the maximum height of bars on the left and right of each position and calculate the water trapped at each position.

Approach

The provided solution uses a two-pointer approach to iterate through the elevation map and calculate the trapped water at each position.

Initialize two pointers, left and right, at the beginning and end of the elevation map, respectively.
Initialize variables leftmax and rightmax to keep track of the maximum height of bars on the left and right, respectively. Set them to the height of the first and last bars.
Initialize a variable res to keep track of the total trapped water.
While the left pointer is less than the right pointer:
If leftmax is less than rightmax, move the left pointer to the right and update leftmax. Calculate and add the trapped water at the current position to res.
If rightmax is less than or equal to leftmax, move the right pointer to the left and update rightmax. Calculate and add the trapped water at the current position to res.
Repeat the process until the pointers meet.

Complexity

  • Time complexity:

The time complexity of this solution is O(n), where n is the length of the input array height. The two-pointer approach allows for a single pass through the elevation map.

  • Space complexity:

The space complexity is O(1), as the solution uses only a constant amount of space to store pointers and variables.

Code

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height: return 0

        left , right = 0 , len(height) - 1
        leftmax,rightmax = height[left] , height[right]
        res=0

        while left < right :
            if leftmax < rightmax:
                left+=1
                leftmax=max(height[left],leftmax)
                res += leftmax - height[left]
            else:
                right-=1
                rightmax=max(height[right],rightmax)
                res += rightmax -height[right]
        
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值