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.
分析:
实现栈的一些函数功能,主要是返回栈顶元素和最小元素。可以定义两个栈s1、s2,s1用来记录栈经过正常入栈出栈之后的元素,s2主要将栈内最小元素放入栈顶。新元素入栈时,与s2栈顶元素比较,如果比之小,则将该元素入栈s1、s2,否则只入栈s1;元素出栈时,比较出栈元素与s2栈顶元素是否相等,若相等,则s1、s2栈顶元素全部出栈,否则只出栈s1栈顶元素。这样求栈顶元素只要返回s1栈顶元素即可;求栈内最小元素只要返回s2栈顶元素即可。
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s1, s2;
MinStack() {
}
void push(int x) {
s1.push(x);
if(s2.empty() || x<=s2.top())
s2.push(x);
}
void pop() {
if(s1.top() == s2.top())
s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
};