单调栈总结

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

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

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 
相关推荐
Sunshine for you19 小时前
如何用FastAPI构建高性能的现代API
jvm·数据库·python
阿贵---19 小时前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python
Red丶哞20 小时前
内网自建Postfix使用Python发送邮件
开发语言·python
rebekk20 小时前
pytorch custom op的简单介绍
人工智能·pytorch·python
chushiyunen20 小时前
uv使用笔记(python包的管理工具)
笔记·python·uv
曲幽20 小时前
FastAPI状态共享秘籍:别再让中间件、依赖和路由“各自为政”了!
python·fastapi·web·request·state·depends·middleware
风清扬【coder】20 小时前
Anaconda 被误删后抢救手册:数据恢复 + 环境重建应急流程
python·数据恢复·anaconda·环境重建
2401_8845632420 小时前
进阶技巧与底层原理
jvm·数据库·python
2401_8732046520 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
l1t20 小时前
DeepSeek 辅助编写python程序求解欧拉计划932题:2025数
开发语言·python·欧拉计划