設計一個棧,除pop與push方法,還支持min方法,可返回棧元素中的最小值。java
push,pop和min三個方法的時間複雜度必須爲O(1)ide
要保證min的時間複雜度爲O(1), 那就不能每次經過遍歷整個棧來獲取最小值。假設這個棧初始爲5:this
5; 最小值爲5; 壓入7,棧變爲spa
7,5;最小值爲5; 壓入3,棧變爲設計
3,7,5; 最小值爲3code
這時彈出3,棧變爲對象
7,5; 最小值爲5; 彈出7, 棧變爲it
5; 最小值爲5;class
注意在7,5這個狀態時,最小值都是5. 也就是說,若是咱們能標記出棧的每一個狀態,那麼能夠直接取出最小值。能夠用一個棧來保存最小值。test
stack類的peek()方法,查看棧頂對象而不移除它
對於棧,實現其min方法很簡單,就是每次push一個值的時候,對minValue進行維護:
if(value < minVlaue){ minValue = value; }
每次調用min() 時直接返回minValue便可。可是,若是pop走的是minValue則須要遍歷剩下的元素求最小值。因此這樣沒法知足O(1)的要求,咱們須要額外的空間保存棧的每個狀態下的最小值。
正如上面陳述的,只要當push的值小於minValue時和pop的值等於minValue時才須要進行額外的操做,用額外的一個棧 stackOfMin來記錄最小值的狀況。當push的值小於minValue時,stackOfMin push新的最小值;pop的值等於minValue時,stackOfMin也相應地pop就行。
//存放最小值的棧 //調用自身Stack的Push方法,而不是StackWithMin2的方法(sMin是Stack類) package test1; import java.util.Stack; public class StackWithMin extends Stack<Integer>{ private Stack<Integer> stackOfMin; public StackWithMin() {stackOfMin = new Stack<>(); } public int min() { if(stackOfMin.isEmpty()){ return Integer.MAX_VALUE; }else { return stackOfMin.peek(); } } @Override public Integer push(Integer item) { if(item < min()){ stackOfMin.push(item);} return super.push(item); } @Override public synchronized Integer pop() { if(this.peek() == min()){ stackOfMin.pop(); } return super.pop(); } public static void main(String[] args) { StackWithMin stackWithMin = new StackWithMin(); stackWithMin.push(19); System.out.println("The min is: "+stackWithMin.min()); stackWithMin.push(15); System.out.println("The min is: "+stackWithMin.min()); stackWithMin.push(17); System.out.println("The min is: "+stackWithMin.min()); stackWithMin.pop(); System.out.println("The min is: "+stackWithMin.min()); stackWithMin.pop(); System.out.println("The min is: "+stackWithMin.min()); stackWithMin.push(30); System.out.println("The min is: "+stackWithMin.min()); stackWithMin.push(1); System.out.println("The min is: "+stackWithMin.min()); stackWithMin.push(4); System.out.println("The min is: "+stackWithMin.min()); } }
The min is: 19 The min is: 15 The min is: 15 The min is: 15 The min is: 19 The min is: 19 The min is: 1 The min is: 1