這裡分類和彙總了欣宸的全部原創(含配套原始碼):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;
}
}