题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
单调队列。
1 class Solution { 2 public: 3 vector<int> maxInWindows(const vector<int>& num, unsigned int size) 4 { 5 vector<int> res; 6 if (size > num.size() || size == 0) return res; 7 deque<int> dq; 8 for (int i = 0; i < size; ++i) { 9 while (!dq.empty() && num[i] >= dq.back()) { 10 dq.pop_back(); 11 } 12 dq.push_back(num[i]); 13 } 14 res.push_back(dq.front()); 15 for (int i = size; i < num.size(); ++i) { 16 if (num[i-size] == dq.front()) dq.pop_front(); 17 while (!dq.empty() && num[i] > dq.back()) { 18 dq.pop_back(); 19 } 20 dq.push_back(num[i]); 21 res.push_back(dq.front()); 22 } 23 return res; 24 } 25 };