Min Stack

来源:互联网 发布:安卓手机java编译 编辑:程序博客网 时间:2024/05/18 00:31

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.

class MinStack {public:    void push(int x) {          m_is.push(x); if(m_isMin.empty() || m_isMin.top()>x) {            m_isMin.push(x); } else //m_is和m_isMin的个数一样多 {m_isMin.push(m_isMin.top()); //再压入一遍 }            }    void pop() {         if(!m_is.empty()) { //不需要比较top值是否相等,再弹出 m_is.pop(); m_isMin.pop(); }    }    int top() {          if(!m_is.empty())  {  return m_is.top();  }  return  0;            }    int getMin() {         if(!m_isMin.empty()) {            return  m_isMin.top(); }    }       public:   stack<int>  m_is;    stack<int>  m_isMin;};


0 0
原创粉丝点击