标签:width space class 队列 names bsp span include code
题目:
题解:
实际上一个滑动窗口可以看成是一个队列,先进先出。
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; }
标签:width space class 队列 names bsp span include code
原文地址:http://www.cnblogs.com/Atanisi/p/7513711.html