设计一个支持 push
,pop
,top
操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack
类:
MinStack()
初始化堆栈对象。void push(int val)
将元素val推入堆栈。void pop()
删除堆栈顶部的元素。int top()
获取堆栈顶部的元素。int getMin()
获取堆栈中的最小元素。
思路一:模拟题意
c++解法
class MinStack {
stack<int> x_stack;
stack<int> min_stack;
public:
MinStack() {
min_stack.push(INT_MAX);
}
void push(int x) {
x_stack.push(x);
min_stack.push(min(min_stack.top(), x));
}
void pop() {
x_stack.pop();
min_stack.pop();
}
int top() {
return x_stack.top();
}
int getMin() {
return min_stack.top();
}
};
分析:
本题要实现一个Minstack类,可以创建一个min_stack栈,栈顶为最小值,每次放入栈的时候判断栈顶和当前数的大小,调用getmin方法时返回min_stack栈顶,pop则两个栈均减少一个元素,实现所有方法后解决
总结:
本题考察对getmin栈的实现,用两个栈分别存储即可解决,时间复杂度为O(1),空间复杂度为O(n)