盛水问题总结

直方图水量

在这里插入图片描述

1、两边收缩~ 好!!!
从两边收缩,因为本来就是通过两边来的,所以两边的最值是可以肯定的。如果左边的最值比右边的最值小,那么左边的水量是可以肯定的,肯定是短板~

class Solution:
    def trap(self, height: List[int]) -> int:
        result = 0
        left = 0
        right = len(height) - 1
        left_max = 0
        right_max = 0

        while left <= right:
            if left_max <= right_max:  # left是短板
                left_max = max(left_max, height[left])
                result += left_max - height[left]
                left += 1
            else:  # right是短板
                right_max = max(height[right], right_max)
                result += right_max - height[right]
                right -= 1
        return result

2、自己的解法
就是一次计算每一个点的左边最值和右边最值,但是会做记录,相当于剪枝。不过还是没有很好的利用好左边和右边比较好的最值。第一种方法最好~~

class Solution:
    def trap(self, nums: List[int]) -> int:
        # 思路就是每一个位置的左边最大和右边最大,取min。
        n = len(nums)
        result = 0
        res1 = 0
        res2 = 0
        for i in range(1, n-1):
            if res2 < i:
                res2 = i + 1
                tmp = res2
                for j in range(tmp, n):
                    if nums[j] > nums[res2]:
                        res2 = j
            if  min(nums[res1], nums[res2]) > nums[i]:
                result += min(nums[res1], nums[res2]) - nums[i]
            if nums[i] >= nums[res1]:
                res1 = i
        return result

3、求出每个柱子的左边的最值和右边的最值。
时间复杂度:预处理出两个最大值数组,复杂度为 O(n)O(n);计算每根柱子可接的雨水量,复杂度为 O(n)O(n)。整体复杂度为 O(n)O(n)。空间复杂度:使用了数组存储两侧最大值。复杂度为 O(n)O(n)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值