LeetCode-42-Trapping Rain Water 贪心或单调栈

这个题一开始想麻烦了,我用单调栈实现了一下,A了,但是只打败了0.4%的人,后来看了一眼别人的博客,发现没那么麻烦,找到最高点,从左右贪心就行了。。。

下面是两份不同做法的代码,时间复杂度都是O(n)


class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        Len=len(height)
        if Len<=1:return 0
        ans=0
        MAX=0
        p=0
        for i in range(0,Len):
            if height[i]>MAX:
                MAX=height[i]
                p=i
        cur=height[0]
        for i in range(1,p):
            if cur<height[i]:
                cur=height[i]
            else:
                ans+=cur-height[i]
        
        cur=height[Len-1]
        for i in range(Len-2,p,-1):
            if cur<height[i]:
                cur=height[i]
            else:
                ans+=cur-height[i]
        return ans
                
            
                
                


class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        Len=len(height)
        if Len<=1:return 0
        stack=[]
        stack.append((height[0],0))
        ans=0
        #print "len",Len
        for i in range(1,Len):
            print i
            stackSize=len(stack)
            if height[i]<stack[stackSize-1][0]:
                #print"fuck1"
                stack.append((height[i],i))
                print stack
            elif height[i]==stack[stackSize-1][0]:
                #print "fuck2"
                stack.pop()
                stack.append((height[i],i))
            else:
                #print"fuck"
                hereH=height[i]
                V=0
                lowest=stack.pop()
                V+=lowest[0]
                stackSize-=1
                while(stackSize>0 and stack[stackSize-1]<=lowest[0]):
                    lowest=stack.pop()
                    V+=lowest[0]
                    stackSize-=1
                higher=(-1,-1)
                V-=lowest[0]
                while stackSize>0 and stack[stackSize-1]>=lowest[0]:
                    higher=stack.pop()
                    V+=lowest[0]*(lowest[1]-higher[1])
                    #print "V",V
                    stackSize-=1
                    if higher[0]>=hereH:
                        stack.append(higher)
                        break
                    lowest=higher
                if higher[0]!=-1:
                    ans+=min(higher[0],hereH)*(i-higher[1]-1)-V
                    #print "ans",ans,V
                    if higher[0]==hereH:
                        stack.pop()
                stack.append((hereH,i))
        return ans
            
                
                


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值