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
相关推荐
爱敲代码的TOM7 分钟前
数据结构总结
数据结构
CoderCodingNo16 分钟前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
大闲在人26 分钟前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
小熳芋29 分钟前
443. 压缩字符串-python-双指针
算法
0思必得030 分钟前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Charlie_lll39 分钟前
力扣解题-移动零
后端·算法·leetcode
chaser&upper40 分钟前
矩阵革命:在 AtomGit 解码 CANN ops-nn 如何构建 AIGC 的“线性基石”
程序人生·算法
沈浩(种子思维作者)43 分钟前
系统要活起来就必须开放包容去中心化
人工智能·python·flask·量子计算
2301_790300961 小时前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
weixin_499771551 小时前
C++中的组合模式
开发语言·c++·算法