您的位置:首页 > 其它

实现能够返回最小值元素的栈(每日一道算法题)

2017-11-11 17:34 288 查看

实现能够返回最小值元素的栈

package stack;

import java.util.Stack;
/**
* @author:MindMrWang
*2017年11月11日
*:function:实现一个特殊的栈,在实现栈基本功能的基础上,再返回栈中最小元素的操作
*          pop push getMin 时间复杂度都是O(1),实现栈的类型可以使用现成的栈结构。
*/

public class MyStack1 {
private Stack<Integer> stackDate;//存值
private Stack<Integer> stackMin;//存最小值

public MyStack1() {
this.stackDate=new Stack<Integer>();
this.stackMin=new Stack<Integer>();
}
//push方法
public void push(int newNum) {
//当stackMin为空的时候,将新值存入stackMin(只执行一次)
if(this.stackMin.isEmpty()) {
this.stackMin.push(newNum);
} else if (newNum<=this.getmin()){//当新值小于等于最小值时,将新值存入stackMin
this.stackMin.push(newNum);

}
this.stackDate.push(newNum);//每次必将值存入stackDate
}

public int pop() {
//判断stackDate是否为空
if(this.stackDate.isEmpty()) {
throw new RuntimeException("your stack is empty");
}
//获得stackDate栈顶元素
int value=this.stackDate.pop();
//如果这个值等于stackMin的栈顶元素将stackMin pop
if(value==this.stackMin.peek()) {
this.stackMin.pop();
}
return value;
}

public int getmin() {
if(this.stackMin.isEmpty()) {
throw new RuntimeException("your stack is empty");
}
return this.stackMin.peek();
}
}


package stack;

import java.util.Stack;

/**
* @author:MindMrWang
*2017年11月12日
*:function:同上
*/
public class MyStack02 {
private Stack<Integer> stackDate;
private Stack<Integer> stackMin;

public MyStack02() {
this.stackDate = 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{
this.stackMin.push(this.getMin());
}
this.stackDate.push(newNum);
}

public int pop() {
if(this.stackDate.isEmpty()) {
throw new RuntimeException("your stack is Empty");
}
this.stackMin.pop();
return this.stackDate.pop();
}

public int getMin() {
if(this.stackDate.isEmpty()) {
throw new RuntimeException("your stack is empty");
}
return this.stackMin.peek();
}
}


方案一压入省空间,且省时间,弹出时稍费时间,方案二压入时候稍费时间,弹出时省时间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐