Monotonic Queue is getting more popular, and finally Leetcode put it on.
Typical solution:element in array would be pushed\popped in\from a sorted data structure, which points to multiset (or any Heap-like data structure). Complexity is O (NLGN).
But with the monotonic Queue, we can solve it in O (n). Http://abitofcs.blogspot.com/2014/11/data-structure-sliding-window-minimum.html
Lesson learnt:monotonic Queue drops elements.
classSolution { Public: Vector<int> Maxslidingwindow (vector<int>& Nums,intk) {vector<int>ret; if(k = =0)returnret; if(k = =nums.size ()) {Ret.push_back (*std::max_element (Nums.begin (), Nums.end ())); returnret; } deque<int> MQ;//Only Store index for(inti =0; I < nums.size (); i++) { if(!mq.empty () && mq.front () <= I-k) Mq.pop_front (); while(!mq.empty () && nums[mq.back ()] <Nums[i]) mq.pop_back (); Mq.push_back (i); if(I >= K-1) Ret.push_back (Nums[mq.front ()); } returnret; }};
Leetcode "Sliding window Maximum"