leetcode【困难】42、接雨水

在这里插入图片描述
思路:
遍历得到当前墙,如果比前一个墙高,加上与前一个墙之间的体积,并接着向前遍历,如果之前有比前一个墙更高的(比当前墙低),再算上增加的体积,最后弹出所有比当前墙低的,以后也不会用上了

注意:每遍历一个墙,要维护一个bottom,接满水的部分就相当于底部升高

class Solution:
    def trap(self, height: List[int]) -> int:
        ans = 0
        stack = []  # 记录遍历过的矮墙
        for i, h in enumerate(height):
            if h == 0:
                continue
            bottom = 0  # 底部,如果之前的坑填满了雨水,就相当于底部升高了
            while stack:
                ii, hh = stack[-1]
                if h >= hh:  # 当前的墙比前面的高
                    ans += (i - ii - 1) * (hh - bottom)
                    bottom = hh
                    # 处理完当前墙的前一面墙
                    #可以接着向前遍历看又没更高的空间
                    #将比当前墙低的都弹出,以后也不会用到了
                    stack.pop()  
                else:  # 当前的墙比前面的矮
                    ans += (i - ii - 1) * (h - bottom)
                    break  # 不用再向前找更高的墙了
            stack.append((i, h))
        return ans

猜你喜欢

转载自blog.csdn.net/qq_40707462/article/details/112984064