總體思想是以空間來換時間,設置兩個棧,其中一個棧放元素,一個棧放最小的值,在push時,判斷新push進去的元素和原先棧中的元素哪個小,小的纔有資格入棧;在pop元素時候,要記得將存放最小值的棧的棧頂元素也pop出來。很簡單。棧的實現用鏈表的實現方式。
/*
* 用O(1)的時間複雜度求棧中的最小元素
*/
public class MyStack1 {
LinkedStack<Integer>elem;
LinkedStack<Integer>min;
public MyStack1(){
elem=new LinkedStack<Integer>();
min=new LinkedStack<Integer>();
}
public void push(int data){
elem.push(data);
if(min.isEmpty()){
min.push(data);
}else{
if(data<min.peek()){
min.push(data);
}
}
}
public int pop(){
int topdata=elem.peek();
elem.pop();
if(topdata==min.peek()){
min.pop();
}
return topdata;
}
public int min(){
if(min.isEmpty()){
return Integer.MAX_VALUE;
}
return min.peek();
}
public static void main(String[] args){
MyStack1 newstack=new MyStack1();
newstack.push(1);
newstack.push(2);
newstack.push(3);
newstack.pop();
System.out.print(newstack.min());//print 1
}
}