单调栈总结

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

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

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 
相关推荐
一只小波波呀41 分钟前
打卡第48天
python
zstar-_1 小时前
一套个人知识储备库构建方案
python
Amo Xiang1 小时前
《100天精通Python——基础篇 2025 第5天:巩固核心知识,选择题实战演练基础语法》
python·选择题·基础语法
江梦寻1 小时前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
霖檬ing1 小时前
Python——MySQL远程控制
开发语言·python·mysql
miniwa2 小时前
Python编程精进:CSV 模块
python
老胖闲聊9 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1189 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之9 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
lyaihao10 小时前
使用python实现奔跑的线条效果
python·绘图