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

单调栈

知识概览

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

例题展示

题目链接

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;
}
相关推荐
不知道取啥耶2 小时前
C++ 滑动窗口
数据结构·c++·算法·leetcode
Murphy_lx2 小时前
数据结构(树)
数据结构
tt5555555555552 小时前
每日一题——三道链表简单题:回文,环形合并有序
数据结构·链表
小六子成长记4 小时前
C语言数据结构之顺序表
数据结构·链表
ChinaRainbowSea8 小时前
MySQL 索引的数据结构(详细说明)
java·数据结构·数据库·后端·mysql
白晨并不是很能熬夜9 小时前
【JVM】字节码指令集
java·开发语言·汇编·jvm·数据结构·后端·javac
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧9 小时前
C语言_数据结构总结7:顺序队列(循环队列)
c语言·开发语言·数据结构·算法·visualstudio·visual studio
橘颂TA9 小时前
每日一练之合并两个有序链表
数据结构·链表
LIUJH12339 小时前
数据结构——单调栈
开发语言·数据结构·c++·算法
shylyly_10 小时前
list的模拟实现
数据结构·c++·链表·迭代器·list·list的模拟实现