41. 包含min函数的栈

包含min函数的栈

描述

设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。

  • push(x)–将元素x插入栈中
  • pop()–移除栈顶元素
  • top()–得到栈顶元素
  • getMin()–得到栈中最小元素

样例

MinStack minStack = new MinStack();
minStack.push(-1);
minStack.push(3);
minStack.push(-4);
minStack.getMin();   --> Returns -4.
minStack.pop();
minStack.top();      --> Returns 3.
minStack.getMin();   --> Returns -1.

代码

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> s;
    stack<int> mins;
    MinStack() {
        
    }
    
    void push(int x) {
        if( mins.empty() || x <= mins.top()){
            mins.push(x);
        }
        s.push(x);
    }
    
    void pop() {
        if(s.top() == mins.top())
            mins.pop();
        s.pop();
    }
    
    int top() {
        return s.top();
    }
    
    int getMin() {
        return mins.top();
    }
};
原文地址:https://www.cnblogs.com/llke/p/10780127.html