您的位置:首页 > 其它

栈和队列——设计一个有getMin功能的栈(二)

2017-08-29 21:05 399 查看
【题目】

  设计一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作

  

【要求】

  1、pop、push、getMin操作的时间复杂度都是O(1)

  2、设计的栈类型可以使用现成的栈结构

    

【代码实现】

import java.util.Stack;
class Mystack2{
private Stack<Integer> stackData;
private Stack<Integer> stackMin;

public Mystack2(){
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);
} else{
int newMin = this.stackMin.peek();
this.stackMin.push(newMin);
}
}
//出栈
public int pop(){
if(this.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();
}
}


【解析】

  这一篇和上一篇的两种对于此问题的解法其实都是用了另一个栈stackMin来保存stackData中的最小值,共同点是所有操作的时间复杂度都是O(1)、空间复杂度都是O(n)。区别是(一)的方案stackMin压入稍省空间,弹出操作稍费时间,(二)的方案stackMin压入稍省费空间,但是弹出稍省时间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  栈和队列