"Disclaimer: All rights reserved, please indicate the source of the reprint, do not use for commercial purposes. Contact mailbox: [Email protected] "
Topic Link:http://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?rp=4&ru=/ta/coding-interviews& Qru=/ta/coding-interviews/question-ranking
Title Description
Given an array and the size of the sliding window, find the maximum value of the values in all the sliding windows. For example, if you enter the array {2,3,4,2,6,2,5,1} and the size of the sliding window 3, there are 6 sliding windows, their maximum value is {4,4,6,6,6,5}, and the sliding window for the array {2,3,4,2,6,2,5,1} has the following 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]}.
Ideas
With two-way queues, we need to maintain the monotony of the queue each time we add elements to the queue.
Class solution{public:vector<int> maxinwindows (const vector<int>& num, unsigned int size) {vector< int> ans;unsigned int len = Num.size (); if (len>=size && size>=1) {deque<int> q;for (unsigned int i = 0 ; i<size; ++i) {while (! Q.empty () && num[q.back ()]<=num[i]) q.pop_back (); Q.push_back (i);} for (unsigned int i = size; i<len; ++i) {ans.push_back (Num[q.front ()]), while (! Q.empty () && num[q.back ()]<=num[i]) q.pop_back (); Q.empty () && Q.front () <= (int) (i-size)) Q.pop_front (); Q.push_back (i);} Ans.push_back (Num[q.front ());} return ans;};
Copyright NOTICE: This article is the original blogger article, if reproduced, please indicate the source
The maximum value of the sliding window for the "offer of Swords"