python leetcode 42. Trapping Rain Water

首先最左边和最右边肯定无法蓄水
考虑能蓄水的情况:左右两边的高度都大于height[i]
所以得左右遍历找到heigh[i]时的左右最大值
再遍历height 当min(maxL[i],maxR[i])>height[i]即能蓄水

class Solution:
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        n = len(height)
        if n<3:return 0 
        right=[0]*n
        maxR=height[-1]
        for j in range(n-2,-1,-1):
            if height[j]>maxR:
                maxR=height[j]
            right[j]=maxR 
        res=0
        maxL=height[0]
        for i in range(1,n-1,1):
            if height[i]>maxL:
                maxL=height[i]
            elif min(maxL,right[i])>height[i]:
                res+=min(maxL,right[i])-height[i] 
        return res

你可能感兴趣的:(leetcode,python)