单调栈总结

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

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

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 
相关推荐
QC·Rex几秒前
AI Agent 任务规划实战:从 ReAct 到 Plan-and-Solve 的完整指南
人工智能·python·react
kcuwu.1 小时前
Python面向对象:封装、继承、多态
开发语言·python
YuanDaima20481 小时前
LangChain基础配置与对话模型实战
人工智能·python·langchain·大模型·智能体·langgraph
河西石头1 小时前
分享python项目与开源python项目中的效率法宝--requirements文件的使用
开发语言·python·requirements文件·批量安装python依赖·python虚拟环境配置
不懒不懒1 小时前
【卷积神经网络作业实现人脸的关键点定位功能】
开发语言·python
Bert.Cai1 小时前
Python集合简介
开发语言·python
tryCbest1 小时前
Java和Python开发项目部署简介
java·开发语言·python
ZTLJQ1 小时前
任务调度的艺术:Python分布式任务系统完全解析
开发语言·分布式·python
敏编程1 小时前
一天一个Python库:isodate - 处理 ISO 8601 日期时间格式
python
Bert.Cai2 小时前
Python字面量详解
开发语言·python