每天两道LeetCodeHard:(7)

126 阅读1分钟

42. Trapping Rain Water

42,捕捉雨水

题干:

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.

解释:

这个题目看图思考会比较直观,题目中的信息给的很少,基本上可以概括为找到凹型结构的最短边然后减去墙的体积就是雨水的体积。

思考:

这个题的思考难点在于,如何减少重复的寻找,因为对任意位置,我们并不知道是否有比它更高的墙,如果每次都遍历整个数组就会造成重复,所以我们应该沿用单调栈的思路,从最高点开始处理,把整个过程分为找左最高点和找右最高点,墙壁和最高点之间的蓄水量相当于已知,剩下的部分递归计算即可,这样就减少了重复.这个思路最后时间97%,感觉非常不错。

答案:

class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        #first to find the highest
        if len(height)==0:
            return 0
        maxIndex =0
        for i in range(len(height)):
            if height[i]>height[maxIndex]:
                maxIndex =i
        return self.findLeft(maxIndex,height)+self.findRight(maxIndex,height)
    def findLeft(self,maxIndex,height):
        if maxIndex ==0:
            return 0
        highest=0
        for i in range(maxIndex):
            if height[i]>height[highest]:
                highest= i
        return self.findLeft(highest,height)+self.helper(highest,maxIndex,height)
    def findRight(self,maxIndex,height):
        if maxIndex == len(height)-1:
            return 0
        highest =len(height)-1
        for i in range(maxIndex+1,len(height)):
            if height[i]>height[highest]:
                highest=i
        return self.findRight(highest,height)+self.helper(maxIndex,highest,height)
    def helper(self,left,right,height):
        sum=0
        for i in range(left+1,right):
            sum+=height[i]
        return min(height[left],height[right])*(right-left-1)-sum

答案补充: