LeetCode-栈的用法-接雨水(python)

36 篇文章 2 订阅
30 篇文章 0 订阅

栈基本概念:https://blog.csdn.net/qq_19446965/article/details/102982047

 

【接雨水】

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water

1、暴力法

找左右柱子的最大值的最小值,即min(l_max,r_max),然后减去自身高度就是能接的雨水

def trap1(height):
    if not height:
        return 0
    res = 0
    for i in range(len(height)):
        l_max = 0
        r_max = 0
        for j in range(i, -1, -1):
            l_max = max(l_max, height[j])
        for j in range(i, len(height)):
            r_max = max(r_max, height[j])

        res = res + min(l_max, r_max) - height[i]

    return res

2、动态规划法

用空间换时间,根暴力法类似,把 L_max、R_max 记录下来,就不用重复计算了

def trap2(height):
    if not height:
        return 0

    res = 0
    n = len(height)
    l_max = [0]*n
    l_max[0] = height[0]
    r_max = [0]*n
    r_max[n-1] = height[n-1]
    for j in range(1, n):
        l_max[j] = max(l_max[j-1], height[j])
    for j in range(n-2, -1, -1):
        r_max[j] = max(r_max[j+1], height[j])
    for i in range(len(height)):
        res = res + min(l_max[i], r_max[i]) - height[i]

    return res

3、双指针法

左边只需要考虑左边,右边只需要考虑右边,各自找到最大值,其余与上述原理类似

def trap3(height):
    if not height:
        return 0

    res = 0
    n = len(height)
    left = 0
    right = n - 1
    l_max = height[0]
    r_max = height[n-1]
    while left < right:
        l_max = max(l_max, height[left])
        r_max = max(r_max, height[right])
        if l_max < r_max:
            res += l_max - height[left]
            left += 1
        else:
            res += r_max - height[right]
            right -= 1

    return res

其余栈的应用:

接雨水:https://blog.csdn.net/qq_19446965/article/details/104144187

矩阵中最大矩形:https://blog.csdn.net/qq_19446965/article/details/82048028

基本计算器类:https://blog.csdn.net/qq_19446965/article/details/104717537

单调栈的应用:https://blog.csdn.net/qq_19446965/article/details/104720836

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值