单调栈总结

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

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

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 
相关推荐
2501_9095091010 分钟前
DAY 28
开发语言·python
码云骑士14 分钟前
71-Agent记忆系统-短期记忆-长期记忆-向量知识库三层架构
python·架构
卷无止境16 分钟前
Python 的 exec 与 eval :动态代码执行的能力、风险与工程实践
后端·python
user-猴子16 分钟前
从零构建 2048 游戏,解析“Python-Use”范式的完整闭环
开发语言·python·游戏
郝学胜_神的一滴26 分钟前
Python 高级编程 025:二分利器bisect模块:优雅维系有序序列,极致优化检索性能
python·pycharm
小陈工42 分钟前
第8篇:Flask轻量级框架与扩展生态深度解析(下)
后端·python·面试
这就是佬们吗1 小时前
Python入门③-运算符、条件与循环
开发语言·数据库·vscode·python·pycharm·编辑器
小刘学技术1 小时前
AI人工智能中的类别不平衡问题:成因、影响与解决方案
开发语言·人工智能·python·机器学习
郝同学今天有进步吗1 小时前
构建 LangGraph Code Review Agent(二):建立仓库路径安全边界
python·ai·code review
雨师@1 小时前
python通过rust编写组件扩展自己的能力
python·rust