isaacpei / algorithm-interview

Weekly algorithm questions for interview
18 stars 0 forks source link

Q002_m75n_solution #18

Open 13o4t opened 6 years ago

13o4t commented 6 years ago

Question_ID: Q002

Language: C++

Time Cost: 40-mins

Time Complexity: O(1)

Solution

维护一个双端队列保存最大值

My Code

#include <iostream>
#include <cstdlib>
#include <string>
#include <queue>
#include <deque>
using namespace std;

template<class T> class MaxQueue {
public:
    void push(const T &elem);
    T pop();
    T get_max();
private:
    queue<T> q;
    deque<T> d;
};

template<class T> void MaxQueue<T>::push(const T &elem)
{
    q.push(elem);
    while (!d.empty() && d.back() < elem)
        d.pop_back();
    d.push_back(elem);
}

template<class T> T MaxQueue<T>::pop()
{
    if (q.empty())
        return -1;

    T res = q.front();
    q.pop();
    if (res == d.front())
        d.pop_front();
    return res;
}

template<class T> T MaxQueue<T>::get_max()
{
    if (d.empty())
        return -1;

    return d.front();
}

int main(void)
{
    MaxQueue<int> que;
    string input;

    while (getline(cin, input)) {
        int idx_split = input.find_first_of(" ", 0);
        string command = input.substr(0, idx_split);
        int arg = atoi(input.substr(idx_split+1).c_str());
        if (command == "push") {
            que.push(arg);
            cout << "None" << endl;
        } else if (command == "pop") {
            cout << que.pop() << endl;
        } else if (command == "get_max") {
            cout << que.get_max() << endl;
        }
    }

    return 0;
}

Other

rbee3u commented 6 years ago

维护一个单调队列,漂亮

ryanorz commented 6 years ago

哇,厉害。我考虑了把最大值放双端队列里,但是没考虑把新来的不够大的值也跟着放队列后面,这里卡住了。

biganans commented 6 years ago

6666