目标:实现一个特殊的栈,在实现栈的基本功能的基础上,实现返回栈中最小的元素的操作
要求:1、pop、push、getMin操作的时间复杂度都是 O(1)
2、设计的栈类型可以使用现成的栈结构
实现:在设计上使用两个栈,一个栈用来保存当前栈中的元素,和正常栈一样,这个栈纪委stackData;另一个栈用于保存每一步操作的最小值,这个栈记为stackMin
第一种设计方案如下:
???压入数据规则:假设当前数据为newNum,将其压入stackData,然后判断stackMin是否为空
如果为空,则newNum也压入stackMin
如果不为空,则比较newNum和stackMin的栈顶元素中哪一个更小
如果newNum更小或者二者相等,则newNum也压入stackMin
如果stackMin中栈顶元素小,则stackMin不压入任何内容
依次压入3、4、5、1、2、1
???弹出数据规则:先在stackData中弹出栈顶元素,记为value,然后比较当前stackMin的栈顶元素和value哪一个更小,stackMin中的元素从栈底到栈顶是逐渐变小的,stackMin栈顶元素是stackData的最小的值,所以value不会比stackMin栈顶元素小
???查询当前栈中最小值操作:stackMin一直记录着stackData中最小的值,所以stackMin栈顶元素是stackData的最小的值
import java.util.Stack;
public class Mystack1 {
//数据存储
private Stack<Integer> stackData;
//存储最小value栈
private Stack<Integer> stackMin;
//构造方法
public Mystack1() {
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);
}
this.stackData.push(newNum);
}
//选
public int pop() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("stack empty");
}
int value = this.stackData.pop();
if (value == this.stackData.pop()) {
this.stackMin.pop();
}
return value;
}
//获取最小值
public int getMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("stack empty");
}
return this.stackMin.peek();
}
}
第一种设计方案如下:
???压入数据规则:假设当前数据为newNum,现将其压入stackData,判断stackMin是否为空:
如果为空,则newNum也压入stackMin
如果不为空,则比较newNum和stackNum和stackMin的栈顶元素中哪一个更小:
如果newNum更小或者相等,则newNum压入newMin;如果newNum更或,则把stackMin的栈顶元素重复压入stackMin,则在栈顶元素上再压入一个栈顶元素。
依次压入3、4、5、1、2、1
???弹出数据规则:在stackData中弹出数据,弹出的数据记为value,弹出stackMin中的栈顶元素,返回value,压入和弹出的规则是对应的
???查询当前栈中最小值操作:stackMin始终记录着stackData中最小的值,stackMin的栈顶元素始终是当前stackData的最小值
import java.util.Stack;
public class Mystack2 {
//数据存储
private Stack<Integer> stackData;
//存储最小value栈
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);
}
this.stackData.push(newNum);
}
//选
public int pop() {
if (this.stackData.isEmpty()) {
throw new RuntimeException("stack empty");
}
this.stackMin.pop();
return this.stackData.pop();
}
//获取最小值
public int getMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("stack empty");
}
return this.stackMin.peek();
}
}