滑动窗口(C++)

样例输入

复制代码
8 3
1 3 -1 -3 5 3 6 7

样例输出

复制代码
-1 -3 -3 -3 3 3
3 3 5 5 6 7

数据范围

对于 20% 的数据,K≤N≤1000;

对于 50% 的数据,K≤N≤10^5;

对于 100% 的数据,K≤N≤10^6。

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

int a[1000006];

void yjc(int n, int w) {
	deque<int> q;
	for (int i = 0; i < n; ++i) {
		while (!q.empty() && a[q.back()] <= a[i]) {
			q.pop_back();
		}
		q.push_back(i);
		if (i >= w - 1) {
			cout << a[q.front()] << ' ';
			if (q.front() == i - w + 1) {
				q.pop_front();
			}
		}
	}
	cout << endl;
}

void xzh(int n, int w) {
	deque<int> q;
	for (int i = 0; i < n; ++i) {
		while (!q.empty() && a[q.back()] >= a[i]) {
			q.pop_back();
		}
		q.push_back(i);
		if (i >= w - 1) {
			cout << a[q.front()] << ' ';
			if (q.front() == i - w + 1) {
				q.pop_front();
			}
		}
	}
	cout << endl;
}

int main() {
	int n, w;
	cin >> n >> w;
	for (int i = 0; i < n; ++i) {
		cin >> a[i];
	}

	xzh(n, w);
	yjc(n, w);

	return 0;
}
相关推荐
FuckPatience3 小时前
C++ 常用类型写法和全称
开发语言·c++
__BMGT()3 小时前
参考文章资源记录
开发语言·c++·qt
ouliten3 小时前
C++笔记:std::string_view
开发语言·c++·笔记
玫瑰花店4 小时前
万字C++中锁机制和内存序详解
开发语言·c++·算法
D_evil__4 小时前
[C++高频精进] 文件IO:文件流
c++
西幻凌云4 小时前
认识STL序列式容器——List
开发语言·c++·stl·list·序列式容器
Elias不吃糖5 小时前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
Want5955 小时前
C/C++跳动的爱心②
c语言·开发语言·c++
初晴や5 小时前
指针函数:从入门到精通
开发语言·c++
铁手飞鹰5 小时前
单链表(C语言,手撕)
数据结构·c++·算法·c·单链表