[LeetCode Python3] 42. Trapping Rain Water 两种解法

42. Trapping Rain Water

Solution 1:

解题思路:
[LeetCode Python3] 42. Trapping Rain Water 两种解法_第1张图片
先计算出黑色和蓝色的面积之和,再减去黑色的面积得到就是蓝色的面积即截留水的体积。
黑色和蓝色的面积之和:一层一层地计算
黑色面积:为sum(height)

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height:
            return 0
        lo, hi = 0, len(height)-1
        target, boundary = 1, max(height) #计算黑色和蓝色的面积之和,从第一层开始算,最高层为boundary 
        res = 0
        while lo < hi or target <= boundary:
            while lo <= hi and height[lo] < target:
                lo += 1
            while lo <= hi and height[hi] < target:
                hi -= 1
            res += (hi-lo+1) # hi-lo+1为每一层的宽度
            target += 1
        return res - sum(height)

Solution 2:官方题解-动态规划

思路:
对于每个位置i,找到0 ~ i的最高位置left_max,和i ~ len(height)-1的最高位置right_max;则当前位置可以截留的水为min(left_max, right_max)-height[i].

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height:
            return 0
        res, size = 0, len(height)
        left_max, right_max = [0]*size, [0]*size
        left_max[0] = height[0]
        for i in range(1, size):
            left_max[i] = max(left_max[i-1], height[i])
        right_max[-1] = height[-1]
        for i in range(size-2, -1, -1):
            right_max[i] = max(right_max[i+1], height[i])
        for i in range(size):
            res += min(left_max[i], right_max[i]) - height[i]
        return res

你可能感兴趣的:(LeetCode每日一题)