轉載摘錄自http://blog.jobbole.com/106940/
問題:實現一個棧,帶有出棧(pop),入棧(push),取最小元素(getMin)三個方法。要保證這三個方法的時間復雜度都是O(1)。
解決方案:
1、設原有的棧為棧A,創建額外的棧B。用於輔助原棧A。
2、當第一個元素入A棧時,將新元素的下標進入棧B,此時棧B的棧頂元素是棧A當前最小值的下標。
3、每當新元素進入棧A時,比較新元素和棧A當前最小值的大小,如果小於棧A當前最小值,則讓新元素的下標進入棧B,此時棧B的棧頂元素就是棧A當前最小值的下標。
4、每當棧A有元素出棧時,如果出棧元素是棧A當前最小值,則讓棧B的棧頂元素也出棧。此時棧B余下的棧頂元素所指向的,是棧A當中原本第二小的元素,代替剛才的出棧元素 成為了棧A的當前最小值。(備胎轉正)
5、當調用getMin方法的時候,直接返回棧B的棧頂所指向的棧A對應元素即可。
另外在評論里面得到另外的一種解決方案:
對於節點額外的增加一個字段,記錄當前為止棧的最小值
package cn.com.duanyi; public class MinStack { public Elem top; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(top == null){ top = new Elem(x, x); }else{ Elem e = new Elem(x, Math.min(x,top.min)); e.next = top; top = e; } } public void pop() { if(top == null) return; Elem temp = top.next; top.next = null; top = temp; } public int top() { if(top == null) return -1; return top.value; } public int getMin() { if(top == null) return -1; return top.min; } public static void main(String[] args) { MinStack minStack=new MinStack(); minStack.push(4); minStack.push(8); minStack.push(3); minStack.push(5); minStack.push(2); minStack.pop(); System.out.println(minStack.getMin()); } } class Elem{ public int value; public int min; public Elem next; public Elem(int value, int min){ this.value = value; this.min = min; } }