设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) – 将元素 x 推入栈中。
- pop() – 删除栈顶的元素。
- top() – 获取栈顶元素。
- getMin() – 检索栈中的最小元素。
示例:
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 {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
data.push(x);
//维护辅助栈
//如果当前元素大小 小于辅助栈顶元素,则将当前元素放入辅助栈中
if (min_stack.empty()) {
min_stack.push(x);
} else {
if (x < min_stack.top()) {
min_stack.push(x);
} else {
min_stack.push(min_stack.top());
}
}
}
void pop() {
data.pop();
min_stack.pop();
}
int top() {
return data.top();
}
int getMin() {
return min_stack.top();
}
private:
stack<int> min_stack;
stack<int> data;
};
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(data.empty()){
data.push(x);
data.push(x);
} else {
if (x >= data.top()) {
int tmp = data.top();
data.push(x);
data.push(tmp);
} else {
data.push(x);
data.push(x);
}
}
}
void pop() {
data.pop();
data.pop();
}
//返回时需先保存栈顶的最小元素
int top() {
int tmp = data.top();
data.pop();
int result = data.top();
data.push(tmp);
return result;
}
int getMin() {
return data.top();
}
private:
stack<int> data;
};