设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
把每次的最小值(之前最小值和新压入栈元素较小者)都保存在辅助栈中。辅助栈的栈顶元素永远保存当前最小值。
class MinStack {
stack<int> st;
stack<int> min;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
st.push(x);
if (min.empty() || x < min.top()) {
min.push(x);
} else {
min.push(min.top());
}
}
void pop() {
st.pop();
min.pop();
}
int top() {
return st.top();
}
int getMin() {
return min.top();
}
};
如果当前元素大于栈顶元素,则不压入(节省一定空间),而在上一种方法中则重复压入最小栈栈顶元素(节省弹出时间)。
class MinStack {
stack<int> st;
stack<int> minStack;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
st.push(x);
if (minStack.empty() || minStack.top() >= x) {
minStack.push(x);
}
}
void pop() {
if (st.top() == minStack.top()) {
minStack.pop();
}
st.pop();
}
int top() {
return st.top();
}
int getMin() {
return minStack.top();
}
};
原文:https://www.cnblogs.com/galaxy-hao/p/12458890.html