单调栈总结

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

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

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 
相关推荐
lntu_ling1 小时前
Python-基于Haversine公式计算两点距离
开发语言·python·gis算法
哈里谢顿7 小时前
Django 应用 OOM(Out of Memory)故障的定位思路和排查方法
python·django
甄心爱学习8 小时前
【python】获取所有长度为 k 的二进制字符串
python·算法
tuotali20269 小时前
氢气压缩机技术规范亲测案例分享
人工智能·python
嫂子的姐夫9 小时前
030-扣代码:湖北图书馆登录
爬虫·python·逆向
a1117769 小时前
EasyVtuber(或其衍生/增强版本)的虚拟主播(Vtuber)面部动画生成与直播解决方案
python·虚拟主播
lintax10 小时前
计算pi值-积分法
python·算法·计算π·积分法
小凯1234510 小时前
pytest框架-详解(学习pytest框架这一篇就够了)
python·学习·pytest
逻极10 小时前
pytest 入门指南:Python 测试框架从零到一(2025 实战版)
开发语言·python·pytest