双栈实现
构造dataStack 、minStack
class MinStack {
private:
stack<int> dataStack;
stack<int> minStack;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
dataStack.push(x); //输入x <= 辅助栈顶,都要压入,否则dataStack.pop()两次相同的最小值时,而minStack只能满足pop()一次,所以出错
if ( minStack.empty() || x <= minStack.top() ){
minStack.push(x);
}
}
void pop() {
if ( dataStack.top() == minStack.top() ){
minStack.pop();
}
dataStack.pop();
}
int top() {
// int res = dataStack.top();
// return res;
return dataStack.top();
}
int getMin() {
// int res = minStack.top();
// return res;
return minStack.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
单栈实现
构造stack<pair<int , int> > minStack;
min = INT_MAX;
class MinStack {
private:
//设置min为最大整数
int min = INT_MAX;
stack<pair<int, int>> minStack;
public:
/** initialize your data structure here. */
MinStack() {}
void push(int x) {
//找到最小值,和x一起存入到pair中
if (x < min) {
min = x;
}
minStack.push(make_pair(min, x));
}
void pop() {
//pop()之后,需要更新min值,分两种情况 1)为空了,min = INT_MAX;
// 2)不空,min = minStack.first;当前栈顶的pair第一个元素(也就是次最小值)赋给min
minStack.pop();
if (minStack.empty()) {
min = INT_MAX;
}
else {
min = minStack.top().first;
}
}
int top() {
return minStack.top().second;
}
int getMin() {
return minStack.top().first;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/