Question:
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
分析:
方法1:
利用两个栈,栈1作为MinStack,栈2按序存放最小值,比如输入为5、4、2、1、1、7则栈2为5、4、2、1、1.在出栈的时候注意,如果出栈的值等于最小值,则将栈2中的栈顶删除;
代码如下:
<span style="font-size:14px;">class MinStack {
private:
stack<int> s1;
stack<int> s2;
public:
void push(int x) {
s1.push(x);
if (s2.empty() || x <= getMin()) s2.push(x);
}
void pop() {
if (s1.top() == getMin()) s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
};</span>
方法2:
利用pair<int,int>,第一个值记录如栈值,第二个记录到此为止的最小值。
代码如下:
<span style="font-size:14px;">public:
void push(int x) {
int min;
if (st.empty()) {
min = x;
}
else {
min = st.top().second<x? st.top().second:x;
}
pair<int, int>p(x, min);
st.push(p);
}
void pop() {
st.pop();
}
int top() {
return st.top().first;
}
int getMin() {
return st.top().second;
}</span>
方法3:
理论同上,方法实现不同。
代码如下
<span style="font-size:14px;">public:
vector<int> stack;
vector<int> min;
MinStack(){
min.push_back(INT_MAX);
}
public:
void push(int x) {
stack.push_back(x);
if(x < min.back())
min.push_back(x);
else
min.push_back(min.back());
}
void pop() {
stack.pop_back();
min.pop_back();
}
int top() {
return stack.back();
}
int getMin() {
return min.back();
}</span>