码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Min Stack

时间:2015-07-06 23:17:01      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

 

Hide Tags
 Stack Data Structure
 

 

 

class MinStack {
    private:
        vector<int> m_data;
        vector<int> m_min;
    public:
        void push(int x) {
            if(m_data.size() == 0)
                m_min.push_back(x);
            else
            {
                if(m_min[m_min.size() - 1] > x)
                    m_min.push_back(x);
                else
                    m_min.push_back(m_min[m_min.size() - 1]);
            }   
            m_data.push_back(x);
        }   

        void pop() {
            m_data.pop_back();
            m_min.pop_back();
        }   

        int top() {
            int size = m_data.size();
            if(size > 0)
                return m_data[size - 1]; 
            else
                return -1; 
        }   

        int getMin() {
            int size = m_min.size();
            if(size > 0)
                return m_min[size - 1];
            else
                return -1;

        }
};

 

[LeetCode] Min Stack

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4625615.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!