单调栈与单调队列算法总结

单调栈

知识概览

  • 单调栈最常见的应用是找到每一个数离它最近的且比它小的数。
  • 单调栈考虑的方式和双指针类似,都是先想一下暴力做法是什么,然后再挖掘一些性质如单调性,最终可以把目光集中在比较少的状态中,从而达到降低时间复杂度的作用,都是算法优化的一种手段。
  • 对于的情况,更有可能是答案,因此将删掉。最终,剩下的是严格单调上升的序列。

例题展示

题目链接

https://www.acwing.com/problem/content/832/

代码

复制代码
#include <iostream>

using namespace std;

const int N = 100010;

int n;
int stk[N], tt;

int main()
{
    scanf("%d", &n);
    
    for (int i = 0; i < n; i++)
    {
        int x;
        scanf("%d", &x);
        while (tt && stk[tt] >= x) tt--;
        if (tt) printf("%d ", stk[tt]);
        else printf("-1 ");
        
        stk[++tt] = x;
    }
    
    return 0;
}

单调队列

知识概览

  • 单调队列最经典的一个应用是求一下滑动窗口里的最大值或最小值。
  • 用数组模拟栈和队列的效率更高,这里用数组模拟。

例题展示

题目链接

https://www.acwing.com/problem/content/156/

代码

复制代码
#include <iostream>

using namespace std;

const int N = 1000010;

int n, k;
int a[N], q[N];

int main()
{
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);
    
    int hh = 0, tt = -1;
    for (int i = 0; i < n; i++)
    {
        // 判断队头是否已经滑出窗口
        if (hh <= tt && i - k + 1 > q[hh]) hh++;
        while (hh <= tt && a[q[tt]] >= a[i]) tt--;
        q[++tt] = i;
        if (i >= k - 1) printf("%d ", a[q[hh]]);
    }
    puts("");
    
    hh = 0, tt = -1;
    for (int i = 0; i < n; i++)
    {
        // 判断队头是否已经滑出窗口
        if (hh <= tt && i - k + 1 > q[hh]) hh++;
        while (hh <= tt && a[q[tt]] <= a[i]) tt--;
        q[++tt] = i;
        if (i >= k - 1) printf("%d ", a[q[hh]]);
    }
    puts("");
    
    return 0;
}
相关推荐
m0_547486663 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr3 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_33 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.3 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.3 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣3 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9923 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水4 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1014 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
2401_839080544 天前
C++常见八股
数据结构·c++·算法