📜  设计一个队列数据结构以在O(1)时间中获得最小值或最大值

📅  最后修改于: 2021-04-17 13:44:39             🧑  作者: Mango

问题:设计一个数据结构一个SpecialQueue,该队列支持以下操作enque,deque,getMin()或getMax(),其中getMin()操作花费O(1)时间。

例子:

Let the data to be inserted in queue be -
4, 2, 1, 6

Operation     Queue       Output
push(4)         4           -
push(2)        4, 2         -
push(1)       4, 2, 1       -
getMin()      4, 2, 1       1
push(6)      4, 2, 1, 6     -
pop()         2, 1, 6       4
pop()          1, 6         2
pop()            6          1
getMin()         6          6

// Notice the getMin() function call
// It returns the minimum element 
// of all the values present in the queue

方法:想法是如果结构要返回最小元素,则使用双端队列以升序存储,如果结构要返回最大元素,则以降序存储。数据结构的操作定义如下:

征服

  • 将元素插入队列结构。
  • 如果Deque结构的大小为空,则Deque的大小为0。然后,从背面插入元素。
  • 否则,如果Deque结构中有一些元素,则将元素从Deque中弹出,直到Deque的背面大于当前元素,然后最后从背面插入该元素。

双端队列

  • 如果双端队列的第一个元素等于队列的最前面的元素,则同时从队列和双端队列中弹出元素。
  • 否则,从队列的前部弹出元素以保持元素的顺序。

获得最低

返回双端队列的前部元素,以获取队列中当前元素的最小元素。

下面是上述方法的实现:

C++
// C++ implementation to design 
// a queue data structure to get 
// minimum element in O(1) time
  
#include 
  
using namespace std;
  
template 
  
// Structure of the queue
class MinMaxQueue {
public:
      
    // Queue to store the 
    // element to maintain the 
    // order of insertion
    queue Q;
      
    // Doubly ended queue to
    // get the minimum element 
    // in the O(1) time
    deque D;
      
    // Function to push a element
    // into the queue
    void enque_element(T element)
    {
        // If there is no element
        // in the queue
        if (Q.size() == 0) {
            Q.push(element);
            D.push_back(element);
        }
        else {
            Q.push(element);
              
            // Pop the elements out
            // until the element at 
            // back is greater than 
            // current element
            while (!D.empty() && 
               D.back() > element) {
                D.pop_back();
            }
            D.push_back(element);
        }
    }
      
    // Function to pop the element
    // out from the queue
    void deque_element()
    {
        // Condition when the Minimum
        // element is the element at 
        // the front of the Deque
        if (Q.front() == D.front()) {
            Q.pop();
            D.pop_front();
        }
        else {
            Q.pop();
        }
    }
      
    // Function to get the
    // minimum element from 
    // the queue
    T getMin()
    {
        return D.front();
    }
};
  
// Driver Code
int main()
{
    MinMaxQueue k;
    int example[3] = { 1, 2, 4 };
      
    // Loop to enque element
    for (int i = 0; i < 3; i++) {
        k.enque_element(example[i]);
    }
    cout << k.getMin() << "\n";
    k.deque_element();
    cout << k.getMin() << "\n";
}


输出:
1
2