[LeetCode] 42. Trapping Rain Water

题:https://leetcode.com/problems/trapping-rain-water/discuss/17391/Share-my-short-solution.

题目

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.

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!

Example:
input[0,1,0,2,1,0,1,3,2,1,2,1]
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

思路

两种

1.

分别从左右遍历,得出 maxleft[i] 为 下标i左边最大的值;得出 maxright[i] 为 下标i右边最大的值。
最后遍历一次,对于每个坐标,如果 取 min(maxleft,maxright) 与 当前高度比较。看当前位置的面积是多少

2.

该方法更简单。
同时左右遍历 lt = 0 , rt = len(height)-1,对于maxleft = max(maxleft,height[lt]).这表示位置 lt的左边的最大值,如果该值 小于maxright = max(maxright,height[rt])。
可得到位置 lt 处的面积,且lt += 1。
同理 rt进行相应的处理;rt -= 1。
直到 lt > rt 结束。

code

方法 1

from collections import defaultdict

def get_zero():
    return 0

class Solution:
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """

        lt = 0
        rt = len(height) - 1
        maxleft = 0
        maxright = 0
        sumsquare = 0
        while(lt<=rt):
            maxleft = max(maxleft,height[lt])
            maxright = max(maxright,height[rt])
            if maxleft<maxright:
                sumsquare += maxleft - height[lt]
                lt += 1
            else:
                sumsquare += maxright - height[rt]
                rt -= 1
        return sumsquare

方法 2

from collections import defaultdict

def get_zero():
    return 0

class Solution:
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """

        maxleft = defaultdict(get_zero)
        maxright = defaultdict(get_zero)
        maxleft[0] = 0
        maxright[len(height)-1] = 0

        for i in range(1,len(height)):
            maxleft[i] = max(maxleft[i-1],height[i-1])

        for i in range(len(height)-2,-1,-1):
            maxright[i] = max(maxright[i+1],height[i+1])

        sumsquare = 0
        for i in range(len(height)):
            tmpsquare = min(maxleft[i], maxright[i]) - height[i]
            if tmpsquare<0:
                tmpsquare = 0
            sumsquare+= tmpsquare
        return sumsquare

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/81005461