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
相关推荐
旖-旎17 小时前
《LeetCode 130 被围绕的区域 FloodFill DFS 解法》
c++·算法·深度优先·力扣·floodfill
林森lsjs17 小时前
斐波那契数列的 N 种解法:从递归到动态规划的优化之路【算法思考】
算法·动态规划
apcipot_rain18 小时前
计科八股20260616(1)——堆存中位数、链表判环、黑白测试、敏捷开发与瀑布模型、配置管理、持续集成、池化
数据结构·算法·软件工程
闵孚龙1 天前
动态图机制:为什么 PyTorch 调试起来更舒服
人工智能·pytorch·python
JAVA面经实录9171 天前
Java 数据结构与算法 (终极完整学习文档)
java·数据结构·算法
chushiyunen1 天前
langchain4j笔记、tools
笔记·python·flask
程序员三藏1 天前
Web自动化测试详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
在放️1 天前
Python 爬虫 · 第三方代理接入与合规使用
开发语言·爬虫·python
开源Z1 天前
LeetCode 42 · 接雨水:从暴力到双指针的三步优化
算法·leetcode
旖-旎1 天前
《LeetCode 695 岛屿的最大面积 FloodFill DFS 解法》
c++·算法·力扣·深度优先遍历·floodfill