## 题目
设计一个支持 push
,pop
,top
操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack
类:
MinStack()
初始化堆栈对象。void push(int val)
将元素val
推入堆栈。void pop()
删除堆栈顶部的元素。int top()
获取堆栈顶部的元素。int getMin()
获取堆栈中的最小元素
示例 1:
输入:
["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.
提示:
-2^31 <= val <= 2^31 - 1
pop
、top
和getMin
操作总是在 非空栈 上调用push
,pop
,top
, andgetMin
最多被调用3 * 10^4
次
解题
方法一:维护一个最小值
思路
维护一个最小值 min
在每次栈内元素更改(入栈、出栈)时更新该值,检索栈中最小元素时直接返回该元素即可。
代码
class MinStack {
private List<Integer> list;
private int min;
public MinStack() {
list = new ArrayList<>();
min = Integer.MAX_VALUE;
}
public void push(int val) {
min = Math.min(min, val);
list.add(val);
}
public void pop() {
int top = list.remove(list.size() - 1);
if (top == min) {
min = Integer.MAX_VALUE;
for (int num : list) {
min = Math.min(min, num);
}
}
}
public int top() {
return list.get(list.size() - 1);
}
public int getMin() {
return min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
方法二:辅助栈
思路
维护一个最小栈 minStack
,每次入栈时,minStack
入栈最小值,出栈时,minStack
也出栈,检索栈中最小元素时返回 minStack.peek()
。
代码
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
minStack.push(Integer.MAX_VALUE);
}
public void push(int val) {
stack.push(val);
minStack.push(Math.min(minStack.peek(), val));
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
评论区