【LeetCode】42. Trapping Rain Water 解题报告(Python)

题目分析:

这个题可以先找出最大值,然后从两侧逼近最高值,以左侧为例说明:左侧值高则可蓄水(让左侧的值减去当前值),否则更新左侧值然后循环,右侧与左侧思路相同,代码已有注释,不再详细解释。

测试代码:

class Solution:
    def trap(self, height):
        if height == []: return 0
        max_num = max(height)
        #变量分别表示,最高值下标,返回的面积,从左侧开始的坐标
        max_point, res, start = height.index(max_num), 0, 0
        # 从左侧逼近最高值
        for i in range(1, max_point):
            #左侧值高则可蓄水
            if height[start] > height[i]:
                res += height[start] - height[i]
            #否则更新左侧值
            else:
                start = i
        end = len(height) - 1
        j = end - 1
        # 从右侧逼近最高值,与左侧思路相同
        while j > max_point:
            if height[end] > height[j]:
                res += height[end] - height[j]
            else:
                end = j
            j -= 1
        return res

print(Solution().trap([0,1,0,2,1,0,1,3,2,1,2,1]))   #提交时请删除该行

猜你喜欢

转载自blog.csdn.net/L141210113/article/details/88538886