154. 滑动窗口,(单调队列模板题)

154. 滑动窗口 - AcWing题库

给定一个大小为 n≤106 的数组。

有一个大小为 k 的滑动窗口,它从数组的最左边移动到最右边。

你只能在窗口中看到 k 个数字。

每次滑动窗口向右移动一个位置。

以下是一个例子:

该数组为 [1 3 -1 -3 5 3 6 7],k 为 3。

窗口位置最小值最大值
[1 3 -1] -3 5 3 6 7-13
1 [3 -1 -3] 5 3 6 7-33
1 3 [-1 -3 5] 3 6 7-35
1 3 -1 [-3 5 3] 6 7-35
1 3 -1 -3 [5 3 6] 736
1 3 -1 -3 5 [3 6 7]37

你的任务是确定滑动窗口位于每个位置时,窗口中的最大值和最小值。

输入格式

输入包含两行。

第一行包含两个整数 n 和 k,分别代表数组长度和滑动窗口的长度。

第二行有 n 个整数,代表数组的具体数值。

同行数据之间用空格隔开。

输出格式

输出包含两个。

第一行输出,从左至右,每个位置滑动窗口中的最小值。

第二行输出,从左至右,每个位置滑动窗口中的最大值。

输入样例:
8 3
1 3 -1 -3 5 3 6 7
输出样例:
-1 -3 -3 -3 3 3
3 3 5 5 6 7

解析 :

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>
#include<unordered_map>

using namespace std;
typedef long long LL;
const int N = 1e6 + 5;
int n,k;
int a[N];
int q[N];
int main() {
	scanf("%d%d", &n,&k);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
	}
	int hh = 0, tt = -1;
	for (int i = 1; i <= n; i++) {
		if (hh <= tt && q[hh] < i - k + 1)hh++;
		while (hh <= tt && a[q[tt]] >= a[i])tt--;
		q[++tt] = i;
		if (i >= k)printf("%d ", a[q[hh]]);
	}
	cout << endl;
	hh = 0, tt = -1;
	for (int i = 1; i <= n; i++) {
		if (hh <= tt && q[hh] < i - k + 1)hh++;
		while (hh <= tt && a[q[tt]] <= a[i])tt--;
		q[++tt] = i;
		if (i >= k)printf("%d ", a[q[hh]]);
		
	}
	cout << endl;
	return 0;
}

posted @   Landnig_on_Mars  阅读(10)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示