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
相关推荐
千千寰宇15 分钟前
[数据库系统] 数据库系统的设计原理研究
数据结构·数据库·database-opengemini/influxdb·database-dament/达梦
勿信日志15 分钟前
Playwright 元素定位:一个 width>50 过滤器把 42px 的输入框删掉了
python
larance20 分钟前
[菜鸟教程] 机器学习教程十课-Python 机器学习应用
人工智能·python·机器学习
栖凤20 分钟前
Java 的 try-catch 在 Agent 里失效了,我用了 5 个模式才兜住
java·前端·python
聪明蛋子哟22 分钟前
不仅仅是向量检索:结合知识图谱与Tool Calling的混合增强生成(Hybrid RAG)方案
人工智能·算法·知识图谱
Pniubi23 分钟前
力扣55跳跃游戏(贪心)
算法·leetcode·游戏
Yyyyyy~28 分钟前
【python】函数
python
金銀銅鐵29 分钟前
[Java] 借助GUI展示class文件的版本号
后端·python·ai编程
外收内放32 分钟前
Python基础语法练习题(62原始版本及其优化版本)
开发语言·python
棉猴34 分钟前
玩游戏学Python4-字符串
python·游戏·字符串·pygame·玩游戏