题目:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作
要求:1 pop,push,getMin操作的时间复杂度都是O(1)
2 设计的栈类型可以使用现成的栈结构
分析:准备两个栈,第一个栈是data栈,用来保存当前栈中的元素;第二个栈是min栈,用来保存每一步的最小值。
第一个思路是:假设当前数据是newNum,先将其压入data栈,然后判断min栈是否为空:
- 如果为空,则newNum也压入min栈;
- 如果不为空,则比较newNum和min栈顶元素哪一个更小;
- 如果newNum更小或者二者相等,则newNum也压入min栈;
- 如果min栈顶元素更小,则min栈不压入任何内容。
第二个思路是在压数的过程中,min和data一起增长。比如说data栈压入一个4,min栈也跟着压入一个4,data栈下一个压入5,则当前数与min栈的栈顶数比较(即data栈的5和min栈的4相比较),如果当前数比min栈的栈顶数要小,就压当前数,否则就重复压入一个min栈的栈顶。那么在任何时刻,min栈的栈顶就是要求的最小元素。弹出数的时候,也是data栈弹出一个,min栈弹出一个,每一步都维持了一个最小元素跟它一起增长的栈顶。这样的操作就做到了pop,push,getMin操作的时间复杂度都是O(1)。
import java.util.Stack;
public class GetMinStack {
public static class MyStack1 {
private Stack<Integer> stackData;
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.stackData.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
int value = this.stackData.pop();
if (value == this.getmin()) {
this.stackMin.pop();
}
return value;
}
public int getmin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
return this.stackMin.peek();
}
}
public static 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);
}
this.stackData.push(newNum);
}
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();
}
}
public static void main(String[] args) {
MyStack1 stack1 = new MyStack1();
stack1.push(3);
System.out.println(stack1.getmin());
stack1.push(4);
System.out.println(stack1.getmin());
stack1.push(1);
System.out.println(stack1.getmin());
System.out.println(stack1.pop());
System.out.println(stack1.getmin());
System.out.println("=============");
MyStack1 stack2 = new MyStack1();
stack2.push(3);
System.out.println(stack2.getmin());
stack2.push(4);
System.out.println(stack2.getmin());
stack2.push(1);
System.out.println(stack2.getmin());
System.out.println(stack2.pop());
System.out.println(stack2.getmin());
}
}