单调栈总结

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

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

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 
相关推荐
Actinen9 分钟前
【Python】——注释
python
自动化小秋葵35 分钟前
Python入门经典题目
开发语言·python
while(1){yan}1 小时前
数据结构之堆
数据结构·python·算法
凌晨一点的秃头猪1 小时前
Python 常见 bug 总结和异常处理
开发语言·python·bug
mortimer1 小时前
用PySide6 构建一个响应式视频剪辑工具:多线程与信号机制实战
python·ffmpeg·pyqt
新子y1 小时前
【小白笔记】input() 和 print() 这两个函数
笔记·python
文火冰糖的硅基工坊2 小时前
[人工智能-大模型-72]:模型层技术 - 模型训练六大步:①数据预处理 - 基本功能与对应的基本组成函数
开发语言·人工智能·python
Python×CATIA工业智造4 小时前
Pycatia二次开发基础代码解析:组件识别、选择反转与链接创建技术解析
python·pycharm
小宁爱Python4 小时前
从零搭建 RAG 智能问答系统 6:Text2SQL 与工作流实现数据库查询
数据库·人工智能·python·django
m0_748241234 小时前
Java注解与反射实现日志与校验
java·开发语言·python