leetcode42.接雨水

双指针+累计

基本思路

1.利用双指针,找到左右最大的“木板”

2.装多少水取决最短的“木板”,累计装水量(最短“木板”-当前高度)

3.重复1,2步骤,直到双指针相遇

解法代码

func trap(height []int) int {
    lMax,rMax,res:=0,0,0
    left,right:=0,len(height)-1

    for left<right{
        lMax=max(height[left],lMax)
        rMax=max(height[right],rMax)

        if lMax<rMax{
            res+=lMax-height[left]
            left++
        }else{
            res+=rMax-height[right]
            right--
        }
    }

    return res

}

func max(x,y int) int{
    if x>y{
        return x
    }
    return y
}

Last updated