Leetcode: Min Stack

来源:互联网 发布:linux中国开源社区 编辑:程序博客网 时间:2024/04/30 19:28

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.

很简单,在CC150上貌似有,两个堆栈实现。

class MinStack {public:    void push(int x) {        fullStack.push(x);        if (minStack.empty() || x <= minStack.top()) {            minStack.push(x);        }    }    void pop() {        if (fullStack.top() == minStack.top()) {            minStack.pop();        }        fullStack.pop();    }    int top() {        return fullStack.top();    }    int getMin() {        return minStack.top();    }    private:    stack<int> fullStack;    stack<int> minStack;};

0 0
原创粉丝点击