解法1:辅助栈
思想:
push和pop操作本来就是O(1),所以只需要一个辅助栈来实现O(1)的min就好了。
辅助栈B的栈顶就是A中元素的最小值
代码:
class MinStack {
private:
stack<int>A;
stack<int>B;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
A.push(x);
// 这里不要跟单调队列的做法搞混
//在B为空或者新的值小于等于B的top时,将x放入B
if(B.empty() || x <= B.top())
B.push(x);
}
//如果要pop的值和B的top相等,B也pop
void pop() {
if(A.top() == B.top())
B.pop();
A.pop();
}
int top() {
return A.top();
}
int min() {
return B.top();
}
};
解法2:一个栈,两个数据位合成一个单元
思想:
用两个数据位作为一个单元,第一个存储数据本身,第二个存储当前的最小值
代码:
class MinStack {
private:
stack<int>s;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
//为空的时候直接push两次
if(s.empty()){
s.push(x);
s.push(x);
}
//不为空,最小值要比较后再push
else{
int tmp = s.top();
s.push(x);
s.push(x < tmp ? x : tmp);
}
}
void pop() {
s.pop();
s.pop();
}
//top是最小值,所以要pop并保存,再取top
int top() {
int tmp = s.top();
s.pop();
int ret = s.top();
s.push(tmp);
return ret;
}
int min() {
return s.top();
}
};