首页 > 其他分享 >滑动窗口

滑动窗口

时间:2022-11-30 22:12:18浏览次数:36  
标签:窗口 int back pop front 滑动

给定一个数组。

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

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

#include <iostream>
#include <deque>
using namespace std;
const int N = 1e6 + 10;
int a[N];
deque<int> q;

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

  

标签:窗口,int,back,pop,front,滑动
From: https://www.cnblogs.com/leetothemoon/p/16939916.html

相关文章