单调栈总结

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

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

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 
相关推荐
岁月宁静12 小时前
驾驭 AI 这匹野马:深入解析智能体 Harness 工程
vue.js·python
星恒随风13 小时前
Python 基础语法详解(一):从表达式、变量到数据类型
开发语言·笔记·python·学习
888CC++13 小时前
java 并发编程
java·开发语言·python
Dxy123931021613 小时前
python缩放图片如何保证图片质量
python
ZHW_AI课题组14 小时前
腾讯云调用IP定位
人工智能·python·机器学习
zhaoshuzhaoshu14 小时前
Python文件操作详细解析带例子
python
醒醒该学习了!14 小时前
Anaconda安装教程+第一个python例子
开发语言·python
linyanRPA15 小时前
影刀RPA+Python店群自动化实战:自研环境隔离引擎,200店铺并发不卡不串号
python·自动化·rpa
郑洁文16 小时前
面向Web安全的Python渗透测试系统设计与实现
python·安全·web安全