leetcode -- Trapping Rain Water -- 重点

https://leetcode.com/problems/trapping-rain-water/

思路很简单,但是不容易想到。求每一个i的储水量
参考http://www.cnblogs.com/zuoyuan/p/3781453.html

还有很多其他解法:
http://www.cnblogs.com/tenosdoit/p/3812880.html

class Solution(object):
    def trap(self, height):
        """ :type height: List[int] :rtype: int """
        leftmosthigh = []
        leftmax = 0
        for x in height:
            #i左边的最大值,不包括i。所以leftmosthigh【0】 = 0.
            leftmosthigh.append(leftmax)
            leftmax = max(leftmax, x)

        rightmax = 0
        res = 0
        for i in xrange(len(height)-1, -1, -1):
            rightmosthigh = rightmax
            tmp = min(leftmosthigh[i], rightmosthigh)
            if tmp > height[i]:
                res += tmp - height[i]
            rightmax = max(rightmax, height[i])
        return res

你可能感兴趣的:(LeetCode)