An array of size
n ≤ 10
6 is given to you. There is a sliding window of size
kwhich is moving from the very left of the array to the very right. You can only see the
k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example:
The array is [1 3 -1 -3 5 3 6 7], and k is 3.
Input
The array is [1 3 -1 -3 5 3 6 7], and k is 3.
Window position | Minimum value | Maximum value |
---|---|---|
[1 3 -1] -3 5 3 6 7 | -1 | 3 |
1 [3 -1 -3] 5 3 6 7 | -3 | 3 |
1 3 [-1 -3 5] 3 6 7 | -3 | 5 |
1 3 -1 [-3 5 3] 6 7 | -3 | 5 |
1 3 -1 -3 [5 3 6] 7 | 3 | 6 |
1 3 -1 -3 5 [3 6 7] | 3 | 7 |
Your task is to determine the maximum and minimum values in the sliding window at each position.
The input consists of two lines. The first line contains two integers
n and
k which are the lengths of the array and the sliding window. There are
n integers in the second line.
Output
There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values.
Sample Input
8 3 1 3 -1 -3 5 3 6 7Sample Output
-1 -3 -3 -3 3 3 3 3 5 5 6 7
滑动窗口问题——经典面试题。
// 滑动窗口问题:使用单调队列
// C++提交AC,G++提交超时
#include <cstdio>
#include <deque>
#include <cstring>
#include <vector>
#define MAX 1000010
using namespace std;
int a[MAX];
int main() {
int n, k;
while( scanf( "%d%d", &n, &k ) != EOF ) {
memset( a, 0, sizeof( a ) );
for( int i = 0; i < n; i++ ) scanf( "%d", &a[i] );
deque<int> minQ; // 保存最小值的单调队列
deque<int> maxQ; // 保存最大值的单调队列
vector<int> minVec;
vector<int> maxVec;
for( int i = 0; i < n; i++ ) {
while( !minQ.empty() && a[minQ.back()] >= a[i] ) {
minQ.pop_back();
}
minQ.push_back( i );
while( !maxQ.empty() && a[maxQ.back()] <= a[i] ) {
maxQ.pop_back();
}
maxQ.push_back( i );
if( i - k + 1 >= 0 ) {
minVec.push_back( a[minQ.front()] );
maxVec.push_back( a[maxQ.front()] );
if( minQ.front() == i - k + 1 ) minQ.pop_front();
if( maxQ.front() == i - k + 1 ) maxQ.pop_front();
}
}
for( int i = 0; i < minVec.size(); i++ ) {
if( i == 0 ) printf( "%d", minVec[i] );
else printf( " %d", minVec[i] );
}
printf( "\n" );
for( int i = 0; i < maxVec.size(); i++ ) {
if( i == 0 ) printf( "%d", maxVec[i] );
else printf( " %d", maxVec[i] );
}
printf( "\n" );
}
return 0;
}