1. 程式人生 > >【隊列】滑動窗口的最大值

【隊列】滑動窗口的最大值

滑動窗口 () emp turn window 上一個 ios bsp out

題目:

題解:

實際上一個滑動窗口可以看成是一個隊列,先進先出。

Solution 1

#include <iostream>
#include <deque>
#include <vector>

using namespace std;

vector<int>  windowMaxOfArray(vector<int> &nums, int width) {
    vector<int> maxInWidows;
    deque<int> q;
    int n = nums.size();
    
if (n >= width && n > 0) { for (int i = 0; i < width; ++i) { while (!q.empty() && nums[i] >= nums[q.back()]) q.pop_back(); q.push_back(i); } for (int i = width; i < n; ++i) { maxInWidows.push_back(nums[q.front()]);
while (!q.empty() && nums[i] >= nums[q.back()]) q.pop_back(); if (!q.empty() && (i - q.front()) >= width) q.pop_front(); q.push_back(i); } maxInWidows.push_back(nums[q.front()]); } return maxInWidows; }
int main() { int n, width; cin >> n; cin >> width; vector<int> nums(n, 0); for (int i = 0; i < n; ++i) { cin >> nums[i]; } vector<int> res = windowMaxOfArray(nums, width); for (auto num : res) { cout << num << " "; } cout << endl; system("pause"); return 0; }

【隊列】滑動窗口的最大值