1. 程式人生 > >Stack with max and min 查詢堆中最大最小數

Stack with max and min 查詢堆中最大最小數

國外algorithm 課後的一個小quiz:

 Create a data structure that efficiently supports the stack operations (push and pop) and also a return-the-maximum and 

return-the-minimum operation. Assume the elements are reals numbers so that you can compare them.

 建立一個能夠有效支援堆操作(插入與彈出)和返回最大最小數的資料結構,假設元素是我們可以比較的數字。

我們的想法可以這樣:

首先讓我們建立的類繼承stack(之後會重寫push與pop方法),建立stack名為store,放所有的元素。類裡再多建立兩個stack,分別為maxStack和minStack,用於輔助判斷的儲存。

當element元素push插入到我們store堆前時,先進行判斷,如果元素比minStack中pop出的元素小,那麼把這個element push加入到minStack中。同理還要對元素進行是否比maxStack最大元素大進行判斷並且進行相應的操作。  事實上,我們要注意這個細節,maxStack和minStack裡面的元素在這樣的操作中已經有了一個排序,最值的就是最近加入的(這太神奇刺激簡單了不是嗎!)  

當元素出store堆時,也進行判斷,如果元素的值等於相應的最大最小值,就在maxStack和minStack中進行pop操作 (之前已經說了,最大的就是最近加入的,這裡就會很方便直接用pop操作去除最值)

之後我們再包裝一下判斷最大最小的方法為minValue 和maxValue 。程式碼就好了。

具體的Java程式碼如下:

public class FindMaxMin extends Stack{
	
	private Stack minStack;
	private Stack maxStack;
	private Stack store;

	public FindMaxMin (){
		minStack=new Stack();
		maxStack=new Stack();
		store =new Stack();
	}
	public void push(int value){
		
		if(value>=MaxValue()){ //note the sign "=";
			maxStack.push(value);
		}
		if(value<=MinValue()){
			minStack.push(value);
		}
		store.push(value);
		
	}
	public Integer pop(){
		
		int value=store.pop();
		if(value==MaxValue()){
			maxStack.pop();
		}
		if(value==MinValue()){
			minStack.pop();
		}
		return value;
	}
	
   public int MaxValue(){
	   if(maxStack.isEmpty()){
		   return Integer.MIN_VALUE;
	   }else{
		   return maxStack.peek();//return but not remove  the most recently added element
	   }
	   
   }
   public int MinValue(){
	   if(minStack.isEmpty()){
		   return Integer.MAX_VALUE;
	   }else{
		   return minStack.peek();
	   }
	   
   }
   
	  /**
	   * 本地測試
	   * @param args
	   */
   public static void main(String args[]){
	   FindMaxMin test=new FindMaxMin();
	   test.push(9);
	   test.pop();
	   test.push(5);
	   test.push(3);
	   test.push(7);
	   test.push(1);
	   test.pop();
	   System.out.println("the biggest is "+test.MaxValue()+" and the smallest is "+test.MinValue());

   }
   
}