题目
链接:155. 最小栈
难度:Easy
题干
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) -- 将元素 x 推入栈中。
- pop() -- 删除栈顶的元素。
- top() -- 获取栈顶元素。
- getMin() -- 检索栈中的最小元素。
示例1:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
题解
分析
本题本意是用来熟悉语言的内置栈和操作,比较简单,需要考虑的就是“在常数时间内检索到最小元素”。要实现O(1)时间复杂度的获取最少值操作,说明一定是在入栈时处理和维护的。很自然就能想到,可以同时维护两个栈,一个是数据栈、一个是最小值栈,两个栈同步push和pop,即可解决问题。
实现
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
data.push(x);
if(min.empty()) {
min.push(x);
} else {
int top = min.top();
min.push(x < top ? x : top);
}
}
void pop() {
data.pop();
min.pop();
}
int top() {
return data.top();
}
int getMin() {
return min.top();
}
private:
stack<int> data;
stack<int> min;
};