(算法优化) 栈和队列(1)--设计一个有getMin功能的栈
题目:
实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
要求:
1、pop、push、getMin操作的时间复杂度都是O(1)
2、设计的栈类型可以使用现成的栈结构
解析:设置两个栈stackData和stackMin,stackData用来保存压入栈的元素,stackMin用来保存每一步的最小值。当压入stackData中的元素小于或等于stackMin的栈顶元素时,将该元素压入stackMin,否则什么也不做。当弹出stackData的元素等于stackMin的栈顶元素时,将该元素弹出栈stackMin,否则什么也不做。如图所示:
代码如下:
package test;
import java.util.Stack;
public class MyStack1 {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack1() { //技巧:在构造方法中初始化两个栈,当new这个类时两个栈已经创建好。
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 void main(String[] args) {
MyStack1 stack1 = new MyStack1();
stack1.push(3);
stack1.push(1);
stack1.push(2);
stack1.push(1);
int stack = stack1.pop();
int min = stack1.getMin();
System.out.println("弹出栈的元素是 " + stack + "\n当前栈中的最小元素是 " + min);
}
}