1. 程式人生 > 實用技巧 >42. 接雨水

42. 接雨水

給定n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。

上面是由陣列 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種情況下,可以接 6 個單位的雨水(藍色部分表示雨水)。感謝 Marcos 貢獻此圖。

示例:

輸入: [0,1,0,2,1,0,1,3,2,1,2,1]
輸出: 6

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/trapping-rain-water

雙指標水題

class Solution:
    def trap(self, height: List[int]) -> int:
        n
=len(height) lmax=rmax=0 l,r=0,n-1 res=0 while l<r: if height[l]<height[r]: if height[l]>=lmax: lmax=height[l] else: res+=lmax-height[l] l+=1 else:
if height[r]>=rmax: rmax=height[r] else: res+=rmax-height[r] r-=1 return res