lc42. Trapping Rain Water

  1. Trapping Rain Water Hard

4874python

86bash

Favoriteapp

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.ui

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!this

Example:spa

Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6code

類型:Arrayleetcode

思路: 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,迭代get

代碼:python3string

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…

相關文章
相關標籤/搜索