题目:
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每次存最小的数值
class MinStack {
public:
MinStack() {
pStack = new stack<int>;
pHelpStack = new stack<int>;
}
~MinStack() {
delete pStack;
delete pHelpStack;
}
void push(int x) {
pStack->push(x);
if (pHelpStack->empty()) {
pHelpStack->push(x);
} else if (pHelpStack->top() >= x) {
pHelpStack->push(x);
} else {
pHelpStack->push(pHelpStack->top());
}
}
void pop() {
pStack->pop();
pHelpStack->pop();
}
int top() {
return pStack->top();
}
int getMin() {
return pHelpStack->top();
}
private:
stack<int>* pStack;
stack<int>* pHelpStack;
};