题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
解题思路一
public class Solution{
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> helpStack = new Stack<Integer>();//辅助栈
private Integer minValue = Integer.MAX_VALUE;//记录当前栈最小值
public void push(int node) {
if(stack.empty()){
minValue = node;
}else{
if(minValue > node)
minValue = node;
}
stack.push(node);
}
public void pop() { //弹出,空间效率O(N)
Integer value = stack.pop();
if(value == minValue){//如果弹出最小值,借助辅助栈重新找到最小值
minValue = Integer.MAX_VALUE;
while (!stack.empty()){
value = stack.pop();
if(value < minValue)
minValue = value;
helpStack.push(value);
}
//倒插回去
while (!helpStack.empty()){
stack.push(helpStack.pop());
}
}
}
public int top() {
return stack.peek();
}
public int min() {
return minValue;
}
}
解题思路二
public class Solution{
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> littleStack = new Stack<Integer>(); //存放最小值的栈
private Integer minValue = Integer.MAX_VALUE;
public void push(int node) {
if(littleStack.empty()){
littleStack.push(node);
}else{
if(node <= littleStack.peek())
littleStack.push(node);
}
stack.push(node);
}
public void pop() {
if(stack.empty())
return ;//栈空无法弹栈
int popValue = stack.pop();
if(popValue == littleStack.peek())
littleStack.pop(); //同时弹出两栈的最小值
}
public int top() {
return stack.peek();
}
public int min() {
return littleStack.peek();
}
}