leetcode之Min Stack

问题描述如下:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

问题链接

cpp代码如下:elemets如果用vector就会memory limit exceeds.以后看看deque的内存管理是怎样的。

class MinStack {
private:
    deque<int> elements;
    stack<int> min_pos;
public:
    void push(int x) {
        if(elements.size()==0){
            elements.push_back(x);
            min_pos.push(0);
        }else{
            int min_=getMin();
            elements.push_back(x);
            if(x<min_)
                min_pos.push(elements.size()-1);
        }
    }

    void pop() {
        if(!elements.empty()){
            if(min_pos.top()==(int)(elements.size()-1)){
                min_pos.pop();
            }
            elements.pop_back();
        }
    }

    int top() {
        if(!elements.empty())
            return elements[elements.size()-1];
        return -1;
    }

    int getMin() {
        if(!elements.empty())
            return elements[min_pos.top()];
        return -1;
    }
};


猜你喜欢

转载自blog.csdn.net/wocaoqwerty/article/details/41697965
今日推荐