LeetCode 42. Trapping Rain Water (python)

本文介绍了一种用于计算二维地形中能够收集雨水的算法。通过寻找地形中的局部最高点,并利用这些点来确定可以收集雨水的区域及其容量。文章详细解释了算法的实现过程,并给出了一段具体的Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        cache = []            #保存凸出来的柱子
        area = 0
        if len(height) < 3:        #只有两个或者以下的柱子不能存水
            return 0
        for index in range(0, len(height)):
            if index == 0:
                if height[0] > height[1]:
                    cache.append(0)
            elif index <len(height) - 1:
                if height[index] >= height[index - 1] and height[index] >= height[index + 1] and height[index] * 2 != height[index - 1] + height[index + 1]:
                    cache.append(index)
            else:
                if height[index] > height[index - 1]:
                    cache.append(index)
        def simplify(content):            #两个较高的柱子之间,较低的凸台并不能限制存水量
            if len(content) <= 2:
                return content
            else:
                left = height[content[0]]        #左端点高度
                right = height[content[-1]]        #右端点高度
                less = min(left, right)
                temp = [element for element in content if height[element] >= less]        #小于较低柱子没有起到限制作用
                if less == left:
                    ret = []
                    ret.append(temp[0])
                    ret.extend(simplify(temp[1:]))        #如果左边较低,那么中间较高柱子与右端柱子重复该过程
                else:
                    ret = []
                    ret.append(temp[-1])
                    ret = simplify(temp[0:-1]) + ret
                return ret
        cache = simplify(cache)
        for i in range(len(cache) - 1):
            left = cache[i]
            right = cache[i + 1]
            limit = min(height[left], height[right])
            for i in range(left+1, right):
                if height[i] < limit:
                    area += limit - height[i]
        return area
#end def
height = [6,4,2,0,3,2,0,3,1,4,5,3,2,7,5,3,0,1,2,1,3,4,6,8,1,3]
a = Solution().trap(height)
print(a)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值