单调栈总结

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

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

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 
相关推荐
winfredzhang1 小时前
用 Python + wxPython 做一个个人健康饮食管理工具:从记录三餐到综合生活建议
python·wxpython·deepseek·生活习惯管理
Irissgwe1 小时前
十、LangGraph能力详解:工作流的常见模式
python·langchain·ai编程·工作流·langgraph
Merlyn102 小时前
【栈】155. 最小栈
python·算法
SilentSamsara2 小时前
NumPy 进阶:广播机制、ufunc 与向量化计算的工程实践
开发语言·python·青少年编程·性能优化·numpy
林爷万福2 小时前
机器学习在光谱分析中的应用:Python实现
人工智能·python·机器学习
编程探索者小陈2 小时前
接口自动化三件套:JSON Schema 校验 + logging 日志 + Allure 测试报告
开发语言·python
godspeed_lucip2 小时前
LLM和Agent——专题6:Multi Agent 入门(3)
人工智能·python
如此这般英俊2 小时前
手搓Claude Code-第二章 tool_use
人工智能·python·ai·语言模型
geminigoth2 小时前
python入门三:字典、输入、while循环
开发语言·python
Irissgwe3 小时前
十、LangGraph能力详解:LangGraph 的其他特性
python·ai·langchain·langgraph