Lc42 接雨水

从左到右扫描记录当前位置的最大值,存入数组A

从右到左扫描记录当前位置的最大值,存入数组B

A,B对应位置的较小值减去雨水量,就是当前位置可以接的雨水

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height or len(height) == 0:
            return 0
        
        lr,rl =[0]*len(height),[0]*len(height)
        
        maxl = height[0]
        for i in range(0,len(height)):
            maxl = max(maxl,height[i])
            lr[i] = maxl
            
        maxr = height[-1]
        for i in range(len(height)-1,-1,-1):
            maxr = max(maxr,height[i])
            rl[i] = maxr
        
        res = [0] * len(height)
        
        for i in range(0,len(height)):
            res[i] = min(lr[i],rl[i]) - height[i]
            
        return sum(res)

 

你可能感兴趣的:(LeetCode)