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

[LeetCode] Min Stack 栈

时间:2015-03-09 22:23:10      阅读:206      评论: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
 

  这个是通过两个stack 维护,一个辅助栈support 维护非升序的情况,注意需要非升序,一个是用于全部data 维护。
 
#include <iostream>
#include <stack>
using namespace std;

class MinStack {
public:
    stack<int> data;
    stack<int> support;

    void push(int x) {
        if(data.empty()){
            data.push(x);
            support.push(x);
        }
        else{
            data.push(x);
            if(x<=support.top()) support.push(x);
        }
    }

    void pop() {
        if(data.top()==support.top())   support.pop();
        data.pop();
    }

    int top() {
        return data.top();
    }

    int getMin() {
        return support.top();
    }
};
int main()
{
    MinStack myMinStack;
    myMinStack.push(1);
    cout<<myMinStack.getMin()<<endl;
    myMinStack.push(2);
    cout<<myMinStack.getMin()<<endl;
    myMinStack.push(0);
    cout<<myMinStack.getMin()<<endl;
    myMinStack.pop();
    myMinStack.pop();
    cout<<myMinStack.getMin()<<endl;
    myMinStack.pop();
    return 0;
}

 

[LeetCode] Min Stack 栈

标签:

原文地址:http://www.cnblogs.com/Azhu/p/4324442.html

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