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:




沒有留言:

張貼留言