155. Min Stack

来源:互联网 发布:雅思大作文 知乎 编辑:程序博客网 时间:2024/06/06 02:04

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://用vector实现似乎比stack快    stack<int> s;    stack<int> min;        void push(int x) {        if(s.empty()){            min.push(x);        }        else if(min.top()>=x)min.push(x);                s.push(x);    }        void pop() {        int temp=s.top();        s.pop();        if(temp==min.top())min.pop();    }        int top() {        return s.top();    }        int getMin() {        return min.top();    }};


0 0