import java.util.Stack;
public class Solution {
//藉助兩個棧,一個存放所有元素,一個存放比較的元素
Stack<Integer> stack1=new Stack<Integer>();
Stack<Integer> stack2=new Stack<Integer>();
public void push(int node) {
stack1.push(node);
if (stack2.size()==0){
stack2.push(node);
}else {
int min;
//棧頂元素跟這個node進行判斷
if (stack2.peek()<node){
min=stack2.peek();
}else {
min=node;
}
stack2.push(min);
}
}
public void pop() {
stack1.pop();
stack2.pop();
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}
很多數據結構算法問題都會藉助到一個輔助的數據結構,例如本題。