滑动窗口

 目录

数组做法

stl做法 


滑动窗口

 题目链接:acwing 滑动窗口

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

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

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

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

以下是一个例子:

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

窗口位置最小值最大值
[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

注意:

为什么向右移动的时候 要满足a[i-k]==q.front() 

因为 我们还需要不断从队首弹出元素保证队列中的所有元素都是窗口中的,因此当队头元素在窗口的左边的时候,弹出队头。 如果不是窗口左边元素,那么就说明这个点已经被移除了 不需要再出队。例如 1 3 -1 -3 5 3 6 7 当 i = 5 的时候 此时a[i-k] = 3 但是q.front() = -1 ,3已经出队 3不能出队。只有当a[i-k]==q.front() 才能出队

数组做法
// Problem: 滑动窗口
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/156/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

const int N = 2e6+5;

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

int main(){
	
	cin>>n>>k;
	
	for(int i=0;i<n;i++){
		cin>>a[i];
	}	
	
	//找最小值
	int hh=0,tt=-1;
	for(int i=0;i<n;i++){
		if(hh<=tt&&i-q[hh]+1>k){   //保证窗口不包括这个元素了
			hh++;
		}
		while(hh<=tt&&a[q[tt]]>=a[i]){   //如果要进队的下一个数小于队尾,那么队尾出队,下一步加上新来的数
			tt--;
		}
		q[++tt]=i;
		if(i>=k-1){    //下标从0开始,i>窗口后,当队头元素在窗口的左边的时候,弹出队头,由于1,3的时候i还没不满足滑动窗口,所以只能先输出-1
			cout<<a[q[hh]]<<' ';
		}
	}
	

	puts("");
	
	hh=0,tt=-1;
	for(int i=0;i<n;i++){
		if(hh<=tt&&i-q[hh]+1>k){
			hh++;
		}
		while(hh<=tt&&a[q[tt]]<=a[i]){
			tt--;
		}
		q[++tt]=i;
		if(i>=k-1){
			cout<<a[q[hh]]<<' ';
		}
	}
	puts("");
	
	
	return 0;	

}
stl做法 
// Problem: P1886 滑动窗口 /【模板】单调队列
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1886
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

const int N = 2e6+5;

int n,k;
int a[N];
deque<int> q;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);

	cin>>n>>k;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	for(int i=1;i<=n;i++){
		while(!q.empty()&&q.back()>a[i]){
			q.pop_back();
		}
		q.push_back(a[i]);
		if(i-k>=1&&q.front()==a[i-k]){
			q.pop_front();
		}
		if(i>=k){
			cout<<q.front()<<' ';
		}
	}
	cout<<"\n";
	q.clear();
	for(int i=1;i<=n;i++){
		while(!q.empty()&&q.back()<a[i]){
			q.pop_back();
		}
		q.push_back(a[i]);
		if(i-k>=1&&q.front()==a[i-k]){
			q.pop_front();
		}
		if(i>=k){
			cout<<q.front()<<' ';
		}
	}
	cout<<"\n";
	
	
	return 0;	

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值