題目
實現一個特殊的棧,在實現棧的基本功能的基礎上,再實現返回棧中最小元素的操作。
要求
- pop、push、getMin 操作的時間複雜度都是
O(1)
- 設計的棧類型可以使用現成的棧結構
思路一
使用兩個棧,一個棧保存當前棧中的元素,一個棧保存最小值。
private Stack<Integer> stackData = new Stack<Integer>();
private Stack<Integer> stackMin = new Stack<Integer>();
public void push(int x) {
stackData.push(x);
if (stackMin.isEmpty() || x < getMin()) {
stackMin.push(x);
} else {
stackMin.push(getMin());
}
}
public void pop() {
stackData.pop();
stackMin.pop();
}
public int top() {
return stackData.peek();
}
public int getMin() {
return stackMin.peek();
}
思路二
只是用一個棧,將最小值和當前元素都存放進去。
Stack<Integer> stack = new Stack<Integer>();
int min = Integer.MAX_VALUE;
public void push(int x) {
if (x <= min){
stack.push(min);
min = x;
}
stack.push(x);
}
public void pop() {
if (stack.pop() == min){
min = stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}