Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
自己实现一个栈,实现push,pop的操作之外,加上top和getMin的操作
这道题选ArrayList实现,push就是add,pop是remove最后一个元素,top是get最后一个元素,这个没啥说的。问题在于getMin,如何最小化时间复杂度。
getMin的笨方法是循环list,找到最小值,但是时间复杂度是O(N)
如果每次调用getMin都用O(N),显然不可取
思路:
声明一个min变量,在每次add时把min与变量比较,逐渐更新min值
在pop的时候,如果没有把min代表的元素删掉,那么min不用变,如果min是-3,这时要pop(-3),就需要用O(N)更新min值
大声说注意:
更新min值前一定要把min置于最大的整数值,重要的事情说3遍
只给getMin代码,其他的自行脑补吧
public void pop() {
if(stack.get(stack.size() - 1) == min) {
stack.remove(stack.size()-1);
min = Integer.MAX_VALUE;
for(int i = 0; i < stack.size(); i++) {
if(stack.get(i) < min) {
min = stack.get(i);
}
}
} else {
stack.remove(stack.size()-1);
}
return;
}