2018年8月19日 星期日
Algorithm :: Montone queue
Inspire by Leetcode #239
https://leetcode.com/problems/sliding-window-maximum/description/
The purpose is the maintain a queue (FIFO) and get the maximum(or minimum) at any moment in time complexity O(1)
Using two queue (dequeue in c++)
one is normal queue, with FIFO, another is the queue maintains the maximum so far (max queue)
when push(x):
normal_queue: push_back(x)
max_queue: pop() all back element until the back element is larger than x (or the queue is empty), and push_back(x)
when pop():
normal_queue: pop_front() (tmp = front(); pop_front() )
max_queue: if the front of max_queue is tmp, pop_front(). Else, do nothing
( means this maximum element is leaving the queue, time to change to the second largest element)
Take the problem in leetcode for example:
訂閱:
張貼留言 (Atom)
-
(1) Vector Common method: vector<int> v; vector v(10, 0); // {0,0,0,0,0,0,0,0,0,0} v[i] // acc...
-
Inspire by Leetcode #239 https://leetcode.com/problems/sliding-window-maximum/description/ The purpose is the maintain a queue (FIFO) an...
-
Q: For a given size = n array, how to choose k element fairly? A: This is a rather easy question if n is small. What if the size is unkn...
沒有留言:
張貼留言