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.
要想在常数时间内返回最小值,要么就是用常数变量存储最小值并维护,要么就是用有序的数据结构来确保的最小值的access。
方法一:
这里比较麻烦的就是pop操作如果把最小值删除,如果找到下一个最小值。这里在每次最小值更新的时候就把前一任最小值再存一边,非常巧妙。
class MinStack {
public:
stack<int> st;
int minval;
/** initialize your data structure here. */
MinStack() {
minval = INT_MAX;
}
void push(int x) {
if (x <= minval) {
st.push(minval);
minval = x;
}
st.push(x);
}
void pop() {
if (st.top() == minval) {
st.pop();
minval = st.top();
}
st.pop();
}
int top() {
return st.top();
}
int getMin() {
return minval;
}
};
方法二:
用两个栈来维护,一个栈正常存储,一个栈存不断更新的最小值。
class MinStack {
public:
stack<int> st1;
stack<int> st2;
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
st1.push(x);
if (st2.empty() || x <= getMin()) {
st2.push(x);
}
}
void pop() {
if (st1.top() == getMin()) {
st2.pop();
}
st1.pop();
}
int top() {
return st1.top();
}
int getMin() {
return st2.top();
}
};