单调栈总结

自底向上的单调递减栈,一般用来寻找下一个更大的元素。

常见做法是从后往前遍历数组,栈顶元素如果小于当前元素就出栈,保持单调性

python 复制代码
def nextGreaterElements(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n = len(nums)
        stack = []
        res = [-1]*n 
        for i in range(n-1,-1,-1):
            while stack and stack[-1] <= nums[i]:
                stack.pop()
            if stack:
                res[i] = stack[-1]
            stack.append(nums[i])
        return res

自底向上的单调递增栈,一般用来寻找前一个更小的元素。

常见做法是从前往后遍历数组,栈顶元素如果大于当前元素就出栈,保持单调性

python 复制代码
def lastMinerElements(self, nums):
res = [-1]*n 
stack = []
for i in range(len(nums)):
    while stack and  nums[i] < stack[-1]:
        stack.pop()
    if stack:
        res[i] = stack[-1]
    stack.append(nums[i)
return res 
相关推荐
晓131317 分钟前
OpenCV篇——项目(二)OCR文档扫描
人工智能·python·opencv·pycharm·ocr
是小王同学啊~19 分钟前
(LangChain)RAG系统链路向量检索器之Retrievers(五)
python·算法·langchain
AIGC包拥它20 分钟前
提示技术系列——链式提示
人工智能·python·langchain·prompt
孟陬21 分钟前
Python matplotlib 如何**同时**展示正文和 emoji
python
何双新26 分钟前
第 1 课:Flask 简介与环境配置(Markdown 教案)
后端·python·flask
费弗里1 小时前
Python全栈应用开发利器Dash 3.x新版本介绍(2)
python·dash
吴佳浩1 小时前
Python入门指南-AI番外-MCP完整教程:从零开始学会Model Context Protocol
人工智能·python·mcp
加油吧zkf2 小时前
目标检测新纪元:DETR到Mamba实战解析
图像处理·人工智能·python·目标检测·分类
程序员阿超的博客2 小时前
Python 数据分析与机器学习入门 (五):Matplotlib 数据可视化基础
python·信息可视化·数据分析·matplotlib·数据可视化·python教程·pyplot
站大爷IP2 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
python