最小棧的實現


轉載摘錄自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對應元素即可。

  %e6%9c%80%e5%b0%8f%e6%a0%88%e7%9a%84%e5%ae%9e%e7%8e%b03

 

另外在評論里面得到另外的一種解決方案:

  對於節點額外的增加一個字段,記錄當前為止棧的最小值

  

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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM