[Leetcode] 42. Trapping Rain Water

来源:互联网 发布:冰与火之歌第八季 知乎 编辑:程序博客网 时间:2024/06/10 07:32

好巧妙,双指针法,找到顶峰,左边开始数到最大,再从右边开始数到最大。

class Solution(object):    def trap(self, height):        """        :type height: List[int]        :rtype: int        """        if len(height)<=2:            return 0        maxx = (0,-1)        ans = 0        for i in range(0,len(height)):            if height[i] > maxx[1]:                maxx = (i,height[i])        curmax = height[0]        for i in range(0,maxx[0]):            if height[i] > curmax:                curmax = height[i]            else:                ans += curmax - height[i]        curmax = height[len(height)-1]        for i in range(len(height)-1,maxx[0],-1):            if height[i] > curmax:                curmax = height[i]            else:                ans += curmax - height[i]        return ans
                                             
0 0
原创粉丝点击