栈和队列
栈和队列
设计一个有getMin功能的栈
实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
pop push getMin操作的时间复杂度都是O(1)。
可以使用现有的栈的结构。
思路:
使用两个栈,一个栈用来保存当前栈中的元素,其功能和正常的栈一样,记为stackData;另一个栈用来保存每一步的最小值,记为
stackMin
第一种实现方案
-
压入数据规则
假设当前数据为newNum,先将其压入stackData。然后判断stackMin是否为空
如果为空,则newNum也压入stackMin
如果不为空,则比较newNum和stackMin的栈顶元素哪个更小
如果newNum更小或者两者相等,则newNum也压入stackMin
如果stackMin的栈顶元素更小,则stackMin不压入任何元素 -
弹出数据规则
先在stackData中弹出栈顶元素,记为value。然后比较当前stackMin栈顶元素和value哪一个更小
当value等于stackMin的栈顶元素时,stackMin弹出栈顶元素;当value大于stackMin的栈顶元素,stackMin不弹出元素,返回value。 -
查询当前栈中的最小元素操作
stackMin保存了当前栈的最小元素,所以stackMin栈顶始终是stackData中的最小元素。
代码实现
public class MyStack{
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack(){
this.stackData=new Stack<Integer>();
this.stackMin=new Stack<Integer>();
}
public void push(int newNum){
if(this.stackMin.isEmpty()){
this.stackMin.push(newNum);
}else if(newNum<=this.getMin()){
this.stackMin.push(newNum);
}
this.stackData.push(newNum);
}
public int pop(){
if(this.stackData.isEmpty()){
throw new RuntiomeException("Your stack is empty!");
}
int value=this.stackData.pop();
if(value==this.getMin()){
this.stackMin.pop();
}
return value;
}
public int getMin(){
if(this.stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty!");
}
return this.stackMin.peek();
}
}
com from Jhon95