Leetcode Trapping Raining water

twisted-fate發表於2019-06-12

這題沒能想出來 , 看的題解 , 遍歷一遍把水坑用水泥填上 , 計算面積 , 再遍歷一遍原來的面積 , 用填了水泥的面積 - 原來的面試 = 答案

iterate origin
    find maxIndex

filled=[]
max=origin[0]
iterate from left to maxIndex
    if origin[i]<max
        filled[i]=max
    else 
        max=arr[i]
        filled[i]=max

max=origin[len-1]
from right to maxIndex
    if origin[i]<max
        filled[i]=max
    else 
        max=arr[i]
        filled[i]=max

sumFilled = sum(filled)
sumOrigin = sum(origin)

res=sumFilled-sumOrigin

return res
func trap(height []int) int {
    if len(height)==0 {
        return 0
    }
    max:=height[0]
    maxIndex:=0
    for k,v:=range height {
        if v>max {
            max=v
            maxIndex=k
        }
    }

    filled:=make([]int,len(height))
    max1:=height[0]

    for i:=0;i<maxIndex;i++ {
        if height[i]<max1 {
            filled[i]=max1
        } else {
            max1=height[i]
            filled[i]=max1
        }
    }

    endIndex:=len(height)-1
    max2:=height[endIndex]
    for j:=endIndex;j>=maxIndex;j-- {
        if height[j]<max2 {
            filled[j]=max2
        } else {
            max2=height[j]
            filled[j]=max2
        }
    }

    sumFilled:=0
    for _,v:=range filled {
        sumFilled+=v
    }

    sumOrigin:=0
    for _,v:=range height {
        sumOrigin+=v
    }

    return sumFilled-sumOrigin

}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章