Min Stack
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:
- void push(int x) {
- data.push(x);
- if(min.empty()) min.push(x);
- else if(x<=min.top()) {
- min.push(x);
- }
- }
- void pop() {
- if(data.empty()) {
- return;
- }
- int top = data.top();
- if(top == min.top()) {
- min.pop();
- }
- data.pop();
- }
- int top() {
- if(!data.empty())
- return data.top();
- return -1;
- }
- int getMin() {
- if(min.empty()) {
- return -1;
- }
- return min.top();
- }
- private:
- stack<int> data;
- stack<int> min;
- };

浙公网安备 33010602011771号