程序员代码面试指南(左程云)读书笔记
第一章
1.设计一个有getMin功能的栈
题目:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作
要求:1 pop, push,getMin操作时间复杂度都是O(1)
2 设计的栈类型可以使用现成的栈结构
解答:设计上用两栈,一个栈用来保存当前栈中的元素,它的功能和一个正常的栈没有区别,记为stackDate。另一个栈用于保存每一步的最小值,记为stackMin。
方法一
import java.util.Stack;
public class MyStack_01 {
private Stack<Integer> stackDate;
private Stack<Integer> stackMin;
public MyStack_01(){
this.stackDate=new Stack<Integer>();
this.stackMin=new Stack<Integer>();
}
public void push(int newNumber){
if(this.stackMin.isEmpty()){
this.stackMin.push(newNumber);
}else if(newNumber<=this.getMin()){
this.stackMin.push(newNumber);
}this.stackDate.push(newNumber);
}
public int pop(){
if(this.stackDate.isEmpty()){
throw new RuntimeException("your stack is empty!");
}
int value=this.stackDate.pop();
if(value==this.getMin()){
this.stackMin.pop();
}
return value;
}
public int getMin() {
if(this.stackMin.isEmpty()){
throw new RuntimeException("your stack is empty!");
}
//peek() 方法用于查找在此堆栈顶部的对象,无需从堆栈中取出。
return this.stackMin.peek();
}
}
方法二
import java.util.Stack;
public class MyStack_02 {
private Stack<Integer> stackDate;
private Stack<Integer> stackMin;
public MyStack_02(){
this.stackDate=new Stack<Integer>();
this.stackMin=new Stack<Integer>();
}
public void push(int newNumber){
if(this.stackMin.isEmpty()){
this.stackMin.push(newNumber);
}else if(newNumber<this.getMin()){
this.stackMin.push(newNumber);
}else{
int newMin=this.stackMin.peek();
this.stackMin.push(newMin);
}
}
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.stackMin.isEmpty()){
throw new RuntimeException("your stack is empty!");
}
//peek() 方法用于查找在此堆栈顶部的对象,无需从堆栈中取出。
return this.stackMin.peek();
}
}
总结:两种方法都是相同的,用stackMin保存stackDate的最小值,时间复杂度都是O(1),空间复杂度都是O(n)。
区别:方案一stackMin压入稍省空间,但是弹出操作稍费空间。方案二中stackMin压入稍费空间,但是弹出操作稍省空间.