单调栈总结

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

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

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 
相关推荐
新网企兴4 分钟前
2026年陕西做GEO推广,找新网企兴解决获客难题
python·搜索引擎
青 春 记 忆16 分钟前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
for_ever_love__19 分钟前
python基础语法学习: 面向对象的三大特性
开发语言·python·学习
Spider赵毅37 分钟前
Python爬虫踩坑实录:BeautifulSoup使用中的高频问题排查
爬虫·python·beautifulsoup
怪奇云呼军1 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
zmzb01033 小时前
Python课后习题训练记录Day194
python·opencv·计算机视觉
benchmark_cc3 小时前
批量获取量化数据时,如何设置合理的超时和重试机制?——QuantDash 高性能实战指南
开发语言·人工智能·python·pandas·量化·quantdash
2601_966949653 小时前
使用 Pandas 读取批量数据时如何避免内存溢出?QuantDash 量化数据工程师避坑指南
开发语言·python·pandas·tushare·akshare·quantdash
65岁退休Coder3 小时前
LangChain v1.3.4 笔记 - 08 MCP & 相关概念
后端·python·langchain
wdloumiga4 小时前
使用 Construct 3零基础做一些2D小游戏
python·游戏·游戏2d