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.
这个是通过两个stack 维护,一个辅助栈support 维护非升序的情况,注意需要非升序,一个是用于全部data 维护。
#include <iostream> #include <stack> using namespace std; class MinStack { public: stack<int> data; stack<int> support; void push(int x) { if(data.empty()){ data.push(x); support.push(x); } else{ data.push(x); if(x<=support.top()) support.push(x); } } void pop() { if(data.top()==support.top()) support.pop(); data.pop(); } int top() { return data.top(); } int getMin() { return support.top(); } }; int main() { MinStack myMinStack; myMinStack.push(1); cout<<myMinStack.getMin()<<endl; myMinStack.push(2); cout<<myMinStack.getMin()<<endl; myMinStack.push(0); cout<<myMinStack.getMin()<<endl; myMinStack.pop(); myMinStack.pop(); cout<<myMinStack.getMin()<<endl; myMinStack.pop(); return 0; }