实现一个特殊的栈, 在实现栈的基本功能的基础上, 再实现返回栈中最小元素的操作。
【要求】
1. pop、push、getMin操作的时间复杂度都是O(1)。
2. 设计的栈类型可以使用现成的栈结构。
思路:同时维护两个栈结构,一个栈就是正常的栈,另一个栈放当前的最小值,和第一个栈同步操作。
package LinearStructure;
import java.util.Stack;
public class GetMinStack {
Stack<Integer> stackData=new Stack<Integer>();
Stack<Integer> stackMin=new Stack<Integer>();
public void push(int obj){
if(stackMin.isEmpty()){//如果当前最小值栈为空,则直接入栈
stackMin.push(obj);
}else if(obj>stackMin.peek()){//如果当前值大于当前最小值栈的栈顶元素,则再压入一个最小值栈栈顶元素
stackMin.push(stackMin.peek());
}else //当前值小于等于最小值栈栈顶元素,当前值入栈
stackMin.push(obj);
stackData.push(obj);
}
public int pop(){
if(stackData.isEmpty()){
throw new RuntimeException("stack is empty!");
}
stackMin.pop();
return stackData.pop();
}
public int getMin(){
if(stackData.isEmpty()){
throw new RuntimeException("stack is empty!");
}
return stackMin.peek();
}
public static void main(String[] args) {
GetMinStack s = new GetMinStack();
s.push(6);
s.push(5);
s.push(2);
int res = s.getMin();
System.out.println(res);
s.push(7);
res = s.getMin();
System.out.println(res);
s.pop();
s.pop();
res = s.getMin();
System.out.println(res);
}
}