Day48-单调栈

42. 接雨水

42. 接雨水 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        res = 0
        st = []
        for i in range(len(height)):
            while st and height[i]>height[st[-1]]:
                cur = st.pop()
                if not st:
                    break  # 左边没有墙,无法接雨水
                left = st[-1]  # 这里不弹出,只是作为左侧的墙,用于承接
                res += (min(height[left],height[i])-height[cur])*(i-left-1)
            if st and height[i]==height[st[-1]]:
                st.pop()  # 相等情况下,高度为0,接不了雨水
            st.append(i)
        return res

84. 最大矩形

84. 柱状图中最大的矩形 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        nums = [0] + heights + [0]  # 如果最后的单调递增,尾部加0;为了第一个子元素可以正常计算,首部加0
        res = []
        st = []
        for i in range(len(nums)):
            while st and nums[i] < nums[st[-1]]:
                cur = st.pop()
                if not st:
                    break
                left = st[-1]
                s = nums[cur]*(i-left-1)
                res.append(s)
            st.append(i)
        return max(res) if res else 0
相关推荐
Sylvia-girl2 小时前
数组题目之移除元素
算法
智算菩萨2 小时前
【Python小游戏】深度解析Pygame实现2048游戏的完整开发流程(有代码实现)
python·游戏程序·pygame
foundbug9992 小时前
小波分析与粒子群算法结合用于电网潮流优化
算法
嘉嘉嘉7172 小时前
【day 52】神经网络调参指南
python·深度学习·机器学习
测试秃头怪2 小时前
Python测试框架Pytest的参数化
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
深蓝电商API2 小时前
Scrapy 爬虫异常处理与重试机制优化
爬虫·python·scrapy
Morwit2 小时前
*【力扣hot100】 448. 找到所有数组中消失的数字
数据结构·算法·leetcode
朔北之忘 Clancy2 小时前
第二章 分支结构程序设计(2)
c++·算法·青少年编程·竞赛·教材·考级·讲义
爱吃提升2 小时前
如何使用量化工具对模型进行量化优化?
python