设计一种堆栈(stack),它能 push,pop,并且能在常数时间内O(1)找到当前栈中的最小元素。
使用double space方式,用空间换时间:
public class Stack{
int [][]stack;
int top;
public Stack(){
stack = new int[10][2];
top =0;
}
public void push(int a){
if(top == 0)
stack[top][1] = a;
else if(a<stack[top-1][1])
stack[top][1] = a;
else
stack[top][1] = stack[top-1][1];
stack[top][0] = a;
top ++;
}
public int pop(){
if(top>0){
top--;
return stack[top][0];
}
else
return 0;
}
public int findMin(){
if(top>0)
return stack[top-1][1];
else
return 0;
}
public static void main(String args[]){
Stack s = new Stack();
s.push(13);
s.push(5);
s.push(7);
s.push(2);
s.push(9);
s.push(14);
System.out.println(s.findMin());
s.pop();
System.out.println(s.findMin());
s.pop();
System.out.println(s.findMin());
s.pop();
System.out.println(s.findMin());
s.pop();
System.out.println(s.findMin());
s.pop();
System.out.println(s.findMin());
}
}
仅增加一个变量记录最小值,每次pop,push时需重新记录最小值。
public class Stack2 {
int []stack;
int top = 0;
int min = 2147483647;
public Stack2(){
stack = new int[10];
}
public void push(int a){
if(a<min)min=a;
stack[top] = a;
top++;
}
public int pop(){
if(top>0){
top--;
if(top == 0)
min=0;
else if(stack[top] == min){
min = stack[top-1];
for(int i=0;i<top-1;i++)
if(stack[i]<min)min = stack[i];
}
return stack[top];
}
return 0;
}
public int findMin(){
return min;
}
public static void main(String[] args) {
Stack2 s = new Stack2();
s.push(13);
s.push(5);
s.push(7);
s.push(2);
s.push(9);
s.push(14);
System.out.println(s.findMin());
s.pop();//14
System.out.println(s.findMin());
s.pop();//9
System.out.println(s.findMin());
s.pop();//2
System.out.println(s.findMin());
s.pop();//7
System.out.println(s.findMin());
s.pop();//5
System.out.println(s.findMin());
}
}