lc42. Trapping Rain Water

236 阅读1分钟
  1. Trapping Rain Water Hard

4874

86

Favorite

Share 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] Output: 6

类型:Array

思路: 1.countNumber=0 l,r比较,设置标杆值com=min(list[l],list[r]),从小的一端开始遍历 2.比如从左开始遍历, list[l+1]<=com,counNumber添加com-list[l+1], list[l+1]>com,窗口缩小为(l+1,r),重置标杆值com,迭代

代码:python3


class Solution:
    def trap(self, height):
        if len(height)<=2:return 0
        countArea=0
        l,r=0,len(height)-1
        current=0
        startOrEnd=(height[l]<height[r])#true start
        print(startOrEnd)
        biaoganzhi=0
        if startOrEnd:
            biaoganzhi=height[l]
        else:
            biaoganzhi=height[r]
        print(biaoganzhi)

        #标志值
        while l<r:
            if startOrEnd:
                #从min开始遍历
                if height[l+1]>biaoganzhi:
                    print("换一边l")

                    #换一边
                    l=l+1
                    startOrEnd=(height[l]<height[r])#true start
                    print(startOrEnd)
                    if startOrEnd:
                        biaoganzhi=height[l]
                    else:
                        biaoganzhi=height[r]
                    continue
                else:
                    print(countArea)
                    l=l+1
                    countArea=countArea+biaoganzhi-height[l]
                    print(countArea)

            else:
                #从min开始遍历
                if height[r-1]>biaoganzhi:
                    print("换一边r")
                    #换一边
                    r=r-1
                    startOrEnd=(height[l]<height[r])#true start
                    print(startOrEnd)
                    if startOrEnd:
                        biaoganzhi=height[l]
                    else:
                        biaoganzhi=height[r]

                    continue
                else:
                    print(countArea)
                    r=r-1
                    countArea=countArea+biaoganzhi-height[r]
                    print(countArea)

            
        return countArea


if __name__ == '__main__':
    print(Solution().trap([5,4,1,2]))

类似: leetcode.com/problems/pr…

leetcode.com/problems/tr…

leetcode.com/problems/po…