题目
题解思路
当队满时(达到滑动窗口最大值)队头++让队头出队
插入元素时
不断循环
当大于等于队尾时,此时队尾肯定不是之后最大元素了,出队。(等于也出队 ,后面的元素肯定比前面的更有潜力)
当小于或者队空时入队。
这样的操作,保证了每次窗口都是最大值。
参考视频
上面只讲了求最大值,求最小值就是把入队的符号更改即可
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
const int INF = 0x3f3f3f3f;
int a[1000100];
int q[1000100];
int main ()
{
ios::sync_with_stdio(false);
int n,k ,ans1 = 0 , ans2 = INF ;
cin>>n>>k;
for (int i = 1 ; i <= n ; i++ )
cin>>a[i];
int h = 0 , t = - 1 ;
for (int i = 1 ; i <= n ; i++ )
{
if ( h <= t && q[h] < i - k + 1 )
h++;
while(h <= t && a[i] <= a[q[t]])
t--;
t++;
q[t] = i ;
if ( i >= k )
cout<<a[q[h]]<<" ";
}
cout<<"\n";
h = 0 , t = -1 ;
for (int i = 1 ; i <= n ; i++ )
{
if ( h <= t && q[h] < i - k + 1 )
h++;
while(h <= t && a[i] >= a[q[t]])
t--;
t++;
q[t] = i ;
if ( i >= k )
cout<<a[q[h]]<<" ";
}
cout<<"\n";
return 0 ;
}