第76题 Min Stack

来源:互联网 发布:qq宠物挂机软件 编辑:程序博客网 时间:2024/06/05 20:27

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








Solution in C++:
class MinStack {public:    vector<int> stack;    int min;        MinStack(){        min = INT_MAX;    }        void push(int x) {        stack.push_back(x);        if(x<min) min=x;    }    void pop() {        int dele;        if(stack.size()>0){              dele = stack[stack.size()-1];              stack.pop_back();        }              if(dele==min){            min = INT_MAX;            for(int i=0; i<stack.size(); i++)                min=min<=stack[i]?min:stack[i];            }        }                  int top() {        return stack[stack.size()-1];    }    int getMin() {        return min;    }};


0 0
原创粉丝点击