Original blog, reproduced please indicate the source!
# topics
# ideas
Use a double-ended queue in C + + to hold a subscript that may be the maximum of a sliding window, where the first element of the team holds the subscript for the current window's maximum value. Updates the queue when the sliding window changes. Rules for queue updates: (1) The new element is compared to the tail element in turn, and if the tail element is less than the new element, the tail element is deleted until the queue has no value less than the new element. (2) Update the first element of the team, if the first element of the team is not in the new sliding window, delete the first element of the team. (3) Press the subscript of each sliding number into the queue
Find the maximum value of a sliding window with a size of 3 in the array, a column in the queue, and a number in front of the parentheses to indicate the subscript of the number in the array.
# code
1#include <iostream>2#include <vector>3#include <queue>4 using namespaceStd5 6 classSolution {7 Public:8vector<int> Maxinwindows (Constvector<int>& num,unsigned intSize9{Tenvector<int> res;//Store the maximum value of each sliding window Onedeque<int> s;//Save the subscript for the maximum number of sliding windows A - for(unsigned intI=0;i<num.size (); ++i) -{ the //Update queue: Delete values that are less than the new element - while(S.size () && num[s.back ()]<=num[i]) -S.pop_back (); - + //Update queue: Update team first element - if(S.size () && I-s.front () +1>size) +S.pop_front (); A at //Update queue: New element's subscript join queue -S.push_back (i); - - //Storage results - if(size&&i+1>=size) -Res.push_back (Num[s.front ()); in} - returnRes to} +}; - intMain () the{ * unsigned intsize = 3; $ Constvector<int> num = {1,2,3,4,5,6,7,8,9};Panax Notoginseng -Solution solution; theSolution.maxinwindows (num,size); + return0; A} the View Code
# complexity
O (N)
# test Case
"Sword Point offer" the maximum value of the sliding window, C + + implementation