单调栈总结

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

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

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 
相关推荐
全栈练习生32 分钟前
大模型原理之 KV Cache
python·ai
天赐范式43 分钟前
天赐范式第183天:让选择开始生效——育种者方程与选择生效条件
python·数字生命·天赐范式·动态运行时·育种者方程·选择压力·遗传力
benchmark_cc1 小时前
批量行情返回后,怎样把请求失败的股票和正常数据分开?
python·数据分析·pandas·量化交易·股票数据·quantdash
y = xⁿ2 小时前
关于Agent工程落地
前端·人工智能·python
小小张说故事2 小时前
pip 安装慢、超时、报错?一份国内源配置 + 9 个高频报错对照表
python
在世修行2 小时前
干货:长任务反馈
python·长任务
东方芷兰2 小时前
Agent 技术摘要 05 —— BP、SaaS、B2B、C2B、B2C
java·笔记·python·语言模型·自然语言处理
老歌老听老掉牙3 小时前
麻花钻切削过程的力学与效率解析
python·钻头·切削
happylifetree3 小时前
Python27:核心语法-流程控制语句-match模式匹配
python
奋进的LY3 小时前
spacy的安装和使用教程
人工智能·python·深度学习·github