题目
设计栈,实现基本功能的前提下,实现返回栈内最小元素的功能
要求
1.push,pop,getmin()复杂度为O(1)
2.允许使用现成栈结构
解决思路
使用两个栈,stackData和stackMin,stackMin负责存最小值
- 法一:若stackMin为空,新数据直接push进去,否则与stackMin的栈顶元素(也就是当前栈中的最小值)进行比较,如果新加入的数据小,则push进stackMin,否则不操作。
- 法二:基本同于法一,只是在新数据与stackMin的栈顶元素比较时,如果新加入的数据小,则push进stackMin,否则将stackMin的栈顶元素再次push进stackMin中
- 比较:
共同点:都用stackMin存储stackData的最小值,时间复杂度均为O(1),空间复杂度均为O(n)
不同点:法一中,push稍省空间,pop时稍费时间;法二中,push稍费空间,pop稍省时间
源码
法一:
public class Mystack1{
private Stack<Integer> stackMin;
private Stack<Integer> stackData;
public Mystack1(){
this.stackMin=new Stack<Integer>();
this.stackData=new Stack<Integer>();
}
public void push(int newNum){
if(this.stackMin.isEmpty()){
this.stackMin.push(newNume);
}else if(newNum<=this.getmin()){
this.stackMin.push(newNume);
}
this.stackData.push(newNum);
}
public int pop(){
if(this.stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty");
}
if(this.stackData.pop()==this.getmin()){
this.stackMin.pop();
}
return this.stackData.pop();
}
public int getmin(){
if(this.stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty");
}
return this.stackMin.peek();
}
}
法二:
public class Mystack2{
private Stack<Integer> stackMin;
private Stack<Integer> stackData;
public Mystack2(){
this.stackData=new Stack<Integer>();
this.stackMin=new Stack<Integer>();
}
public void push(int newNum){
if(this.staticMin.isEmpty()){
this.staticMin.push(newNum);
}else if(newNum<this.getmin()){
this.staticMin.push(newNum);
}else{
this.staticMin.push(this.getmin());
}
this.stackData.push(newNum);
}
public int pop(){
if(ths.stackData.isEmpty()){
throw new RuntimeException("Your stack is empty");
}
this.stackMin.pop();
return this.stackData.pop();
}
public int getmin(){
if(this.stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty");
}
return this.stackMin.peek();
}
}
如果有什么疑问,随时欢迎留言交流讨论,希望大家一起学习一起进步~