题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。
把每次的最小元素(之前的最小元素和新压入栈的元素两者的较小值)都保存起来放到另外一个辅助栈里。下图展示了栈内压入3、4、2、1之后接连两次弹出栈顶数字再压入0时,数据栈、辅助栈和最小值的状态。
从表中我们可以看出,如果每次都把最小元素压入辅助栈,那么就能保证辅助栈的栈顶一直都是最小元素。
package offer;
import org.junit.Test;
import java.util.Stack;
/**
* 题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min
* @author kankan
* @creater 2019-07-02 19:14
*/
public class StackWithMin {
//存放数据
Stack<Integer> stack_data = new Stack<Integer>();
//栈顶一直都是存放最小元素
Stack<Integer> stack_min = new Stack<Integer>();
public void push(int node){
stack_data.push(node);
if (stack_min.empty() || stack_min.peek() > node){
stack_min.push(node);
}else {
stack_min.push(stack_min.peek());
}
}
public void pop(){
if (! stack_data.empty()){
stack_data.pop();
stack_min.pop();
}
}
public int min(){
return stack_min.peek();
}
//测试案例
@Test
public void test1(){
StackWithMin stack = new StackWithMin();
stack.push(3);
int min = stack.min();
System.out.println(min);
}
//新压入栈的数字比之前的最小值大
@Test
public void test2(){
StackWithMin stack = new StackWithMin();
stack.push(3);
stack.push(4);
System.out.println(stack.min());
}
//新压入栈的数字比之前的最小值大
@Test
public void test3(){
StackWithMin stack = new StackWithMin();
stack.push(3);
stack.push(4);
stack.push(2);
System.out.println(stack.min());
}
//弹出栈的数字是最小的元素
@Test
public void test4(){
StackWithMin stack = new StackWithMin();
stack.push(3);
stack.push(4);
stack.push(2);
stack.pop();
System.out.println(stack.min());
}
//弹出栈的数字不是最小的元素
@Test
public void test5(){
StackWithMin stack = new StackWithMin();
stack.push(3);
stack.push(4);
stack.push(2);
stack.push(3);
stack.pop();
System.out.println(stack.min());
}
}