题目
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
示例:
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
提示:
pop、top 和 getMin 操作总是在 非空栈 上调用。
思路
使用一个数据栈和辅助栈,辅助栈用以存储最小元素的变化值
。例如输入[2, 0, 1],则最小值变化两次,辅助栈中存储[2, 0]。记忆该例子即可写出代码
主要是对于入栈和出栈时需要有所设计
题解
入栈时,需比较的是x <= help.top(),注意等号
c++
class MinStack {
public:
/** initialize your data structure here. */
stack<int> data;
stack<int> help;
MinStack() {
stack<int> data;
stack<int> help;
}
void push(int x) {
data.push(x);
if (help.empty() || x <= help.top()) help.push(x); //空解决第一次入栈的问题,并且注意是小于等于
}
void pop() {
if (data.top() == help.top()) {
data.pop();
help.pop();
}
else data.pop();
}
int top() {
return data.top();
}
int min() {
return help.top();
}
};
java
注意点:
- peek与pop的区别
- data.peek返回的是包装类
Integer
,需要用其类方法.equals()来比较值是否相同
此题如果用==将会无法通过 Integer的equals重写过,比较的是内部value的值, ==如果在[-128,127]会被cache缓存,超过这个范围则比较的是对象是否相同
class MinStack {
Stack<Integer> data; //Java中Stack为一个标准类,因此大写开头
Stack<Integer> help;
/** initialize your data structure here. */
public MinStack() {
data = new Stack<Integer>();
help = new Stack<Integer>();
}
public void push(int x) {
data.push(x);
if (help.empty() || x<=help.peek()) help.push(x); //Java中查看栈顶叫peek(挺形象的),pop会出栈
}
public void pop() {
if (data.peek().equals(help.peek())) help.pop();
data.pop();
}
public int top() {
return data.peek();
}
public int min() {
return help.peek();
}
}
复杂度
时间复杂度 | 空间复杂度 |
---|---|
O(1) | O(1) |