21題目: 定義棧的數據結構,請在該類型中實現一個能夠得到棧的最小素的min 函數。在該棧中,調用min、push 及pop的時間複雜度都是0(1)
/**
* 定義棧的數據結構
* 使得返回最小元素min() pop() push()的時間複雜度都爲O(1)
* @author aa
* @param <T>
*
*/
public class StackWithMin<T> {
// 定義數據棧,用於存放插入的數據
private Stack<T> dataStack;
// 最小數的位置棧,存放數據棧中最小數的位置
private Stack<Integer> minStack;
public StackWithMin(){
this.dataStack = new Stack<>();
this.minStack = new Stack<>();
}
/**
* 出棧
*/
public T pop(){
if(dataStack.isEmpty()){
throw new RuntimeException("This Stack Is Empty");
}
minStack.pop();
return dataStack.pop();
}
/**
* 入棧
*/
public void push(T t){
if(t == null){
throw new RuntimeException("Element Is Empty");
}
// 如果數據棧爲空,直接讓元素入棧,同時更新最小數棧中的數據
if(dataStack.isEmpty()){
dataStack.push(t);
minStack.push(0);
}else{
T e = dataStack.get(minStack.peek());
dataStack.push(t);
if(((Integer) t).compareTo((Integer) e) < 0){
minStack.push(dataStack.size()-1);
}else{
minStack.push(minStack.peek());
}
}
}
/**
* 獲取棧中最小數
*/
public T min(){
if(minStack.isEmpty()){
throw new RuntimeException("No Element In Stack");
}
return dataStack.get(minStack.peek());
}
}
22題目:輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷二個序列是否爲該棧的彈出順序。假設壓入棧的所有數字均不相等。
/**
* 判斷輸出的序列是否爲棧的彈出順序
* @param push
* @param pop
* @return
*/
public static boolean isPopOrder(int[] push, int[] pop){
// 輸入校驗, 參數不可爲空,並且兩個數組中必修有數字,而且連個數組中的數字個數相同
if(push == null || pop == null || pop.length == 0 || push.length == 0 || push.length != pop.length){
return false;
}
// 經過上面參數校驗,保證輸入有數據且數目相等
Stack<Integer> stack = new Stack<>();
// 入棧元素的處理位置
int pushIndex = 0;
// 出棧元素的處理位置
int popIndex = 0;
while(popIndex < pop.length){
while(pushIndex < push.length && (stack.isEmpty() || stack.peek() != pop[popIndex])){
stack.push(push[pushIndex]);
pushIndex++;
}
if(stack.peek() == pop[popIndex]){
stack.pop();
popIndex++;
}else{
return false;
}
}
// 此時返回的必然爲true,因爲如果在棧頂找不到與出棧元素相同的元素
// 則直接慧返回false結束方法,否則證明pop[]爲入棧順序的一個出棧順序
// 那麼必定會執行完,所以stack.isEmpty()必定返回true
return stack.isEmpty();
}