这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos
输入:
["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.
class MinStack {
Deque<Integer> xStack;
Deque<Integer> minStack;
public MinStack() {
xStack = new LinkedList<Integer>();
minStack = new LinkedList<Integer>();
minStack.push(Integer.MAX_VALUE);
}
public void push(int x) {
xStack.push(x);
minStack.push(Math.min(minStack.peek(), x));
}
public void pop() {
xStack.pop();
minStack.pop();
}
public int top() {
return xStack.peek();
}
public int getMin() {
return minStack.peek();
}
}
class MinStack {
private int[] array = new int[64];
private int pointer = -1;
private int min = Integer.MAX_VALUE;
public MinStack() {
}
public void push(int val) {
array[++pointer] = val;
min = Math.min(min, val);
// 扩容
if (pointer==(array.length-1)) {
int[] temp = new int[array.length*2];
System.arraycopy(array, 0, temp, 0, array.length);
array = temp;
}
}
public void pop() {
pointer--;
// 这里可以优化:如果弹出的不是最小值,那就没必要重算呀!
if (array[pointer+1]==min) {
min = Integer.MAX_VALUE;
for (int i=0;i<=pointer;i++) {
min = Math.min(min, array[i]);
}
}
}
public int top() {
return array[pointer];
}
public int getMin() {
return min;
}
}