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
相关推荐
NAGNIP6 小时前
一文搞懂深度学习中的通用逼近定理!
人工智能·算法·面试
AI探索者11 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者11 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh12 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅12 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽14 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
颜酱14 小时前
单调栈:从模板到实战
javascript·后端·算法
两万五千个小时17 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
CoovallyAIHub17 小时前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub17 小时前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉