11-1:(42)接雨水

42. 接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

An understandable python solution:

class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        left = 0
        right = len(height) - 1
        left_max = right_max = area = 0
        
        while left < right:
            if height[left] < height[right]:
                if height[left] < left_max:
                    area += left_max - height[left]
                else:
                    left_max = height[left]
                left += 1
            else:
                if height[right] < right_max:
                    area += right_max - height[right]
                else:
                    right_max = height[right]
                right -= 1
                
        return area

分析:

代码用到了双指针的方法,该方法假设给定的height列表中间全是黑箱,每次只露出height的头部和尾部。

当头部遇到比它小的值时,它们的差值就是当前位置可以填充的雨水的数量;而当头部遇到比它大的值时,是无法填充雨水的,此时头部要更新,将这个更大的值作为新的头部,与后面的数字进行比较。

对尾部的处理用的也是同样的方法。

posted @ 2019-07-10 14:18  mingyu02  阅读(129)  评论(0编辑  收藏  举报