LeetCode 155:Min Stack

来源:互联网 发布:网络性爱小说 编辑:程序博客网 时间:2024/06/05 17:23

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.
设计一个栈支持这些操作,并且在常数时间内返回栈内的最小元素。


依然是用两个栈来满足。其中一个栈正常存放所有元素,另一个栈存放当前栈内的最小元素(在pop的时候需要判断)

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


0 0