42. Trapping Rain Water leetcode Python 2016 new season

来源:互联网 发布:贵阳大数据产业博览会 编辑:程序博客网 时间:2024/06/05 14:08

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example, 
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.


The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Show Tags
Show Similar Problems


class Solution(object):    def trap(self, height):        """        :type height: List[int]        :rtype: int        """        if not height:            return 0        height_len = len(height)        maxLeft = [0 for _ in range(height_len)]        maxRight = [0 for _ in range(height_len)]        max_value = height[0]        for index in range(height_len):            maxLeft[index] = max_value            if max_value < height[index]:                max_value = height[index]        max_value = height[height_len - 1]        for index in reversed(range(height_len)):            maxRight[index] = max_value            if max_value < height[index]:                max_value = height[index]        result = 0        for index in range(height_len):            water = min(maxRight[index], maxLeft[index]) - height[index]            if water > 0:                result += water        return result                









0 0
原创粉丝点击