042 Trapping Rain Water

这道题有一个直观的想法, 就是分别记录每个点的左侧和右侧最大值 对于height[i] 这一点能装的水等于 min(leftMax[i], rightMax[i]) - height[i]. 这个解法需要扫描2次序列。

以下的方法只需要扫描一次序列即可。

class Solution:
    # @param {integer[]} height
    # @return {integer}
    def trap(self, height):
        stack = []
        ans = 0
        i, length = 0, len(height)
        while i < length:
            if stack == []:
                stack.append([height[i], 1])
            else:
                if height[i] < stack[-1][0]:
                    stack.append([height[i], 1])
                else:
                    if height[i] >= stack[0][0]:
                        hh = stack[0][0]
                        while stack != []:
                            col = stack.pop()
                            h = col[0]
                            l = col[1]
                            ans += (hh - h) * l
                        stack.append([height[i], 1])
                    else:
                        tmp = 1
                        hh = height[i]
                        while hh >= stack[-1][0]:
                            col = stack.pop()
                            h = col[0]
                            l = col[1]
                            ans += (hh - h) * l
                            tmp += l
                        stack.append([hh, tmp])
            i += 1
        return ans

 

posted @ 2015-07-09 00:48  dapanshe  阅读(136)  评论(0编辑  收藏  举报