您的位置:首页 > 职场人生

程序员代码面试指南--设计一个具有getMin功能的栈

2018-02-04 16:21 876 查看
/*
设计一个有getMin功能的栈
【题目】
实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回
栈中最小元素的操作。
【要求】
1.pop、push、getMin操作的时间复杂度都是O(1)。
2.设计的栈类型可以使用现成的栈结构。
在设计上我们使用两个栈,一个栈用来保存当前栈中的元素,其
功能和一个正常的栈没有区别,这个栈记为stackData;另一个栈用
于保存每一步的最小值,这个栈记为stackMin。具体的实现方式有两
种
 */
public class C01_GetMinStack {
//方法1:如果栈为空,压入数据,如果不为空并且比栈顶数值小,压入栈,否则不处理
public static class MyStack1{
private Stack<Integer>data;//记录全部数的栈
private Stack<Integer>min;//几录最小值的栈
public MyStack1(){//构造方法new 栈
this.data = new Stack<Integer>();
this.min = new Stack<Integer>();
}
public void push(int num){//压栈
if(min.isEmpty()){
min.push(num);
}else if(num<=getMin()){
min.push(num);
}
data.push(num);
}
public int pop(){//出栈
if(data.isEmpty()){//栈为空就抛出一个运行时异常
throw new RuntimeException("your stack is empty");
}
int value = data.pop();
if(value==getMin()){//相等时出栈
min.pop();
}
return value;
}
public int getMin(){
if(min.isEmpty()){
throw new RuntimeException("your stack is empty");
}
return min.peek();
}
}

//方法2:min为空或者num大于栈顶直接压入,num小于等于min的栈顶就压入num
public static class MyStack2{
private Stack<Integer>data;
private Stack<Integer>min;
public MyStack2(){
this.data = new Stack<Integer>();
this.min = new Stack<Integer>();
}
public void push(int num){
if(min.isEmpty() || num<=getMin()){
min.push(num);
}else if(num<=getMin()){
min.push(getMin());
}
data.push(num);
}
public int pop(){
int value = data.pop();
min.pop();
return value;
}
public int getMin(){
if(min.isEmpty()){
throw new RuntimeException("your stack is empty");
}
return min.peek();
}
}

public static void main(String[] args) {
MyStack1 stack1 = new MyStack1();//2 2 0 0 2
stack1.push(2);
System.out.println(stack1.getMin());
stack1.push(5);
System.out.println(stack1.getMin());
stack1.push(0);
System.out.println(stack1.getMin());
System.out.println(stack1.pop());
System.out.println(stack1.getMin());

System.out.println("---------------");

MyStack2 stack2 = new MyStack2();//2 2 0 0 2
stack2.push(2);
System.out.println(stack2.getMin());
stack2.push(5);
System.out.println(stack2.getMin());
stack2.push(0);
System.out.println(stack2.getMin());
System.out.println(stack2.pop());
System.out.println(stack2.getMin());
}
}

//方案一和方案二其实都是用stackMin栈保存着stackData每一步的
//最小值。共同点是所有操作的时间复杂度都为O(1)、空间复杂度都为
//O(n)。区别是:方栗一中stackMin压入时稍省空间,但是弹出操作稍
//费时间;方案二中stackMin压入时稍费空间,但是弹出操作稍省时间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: