设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
1.双栈解法
使用2个栈,一个存放具体数值,另一个存放最小值
dataStack:存放具体数值的栈
minStack:存放栈的最小元素
import java.util.Stack;
//双栈解法
class MinStack {
private Stack<Integer> dataStack;// 存放具体数值的栈
private Stack<Integer> minStack;// 存放栈的最小元素
public MinStack() {
this.dataStack = new Stack<>();
this.minStack = new Stack<>();
}
public void push(int x) {
if(minStack.isEmpty()||x<=minStack.peek()){
minStack.push(x);
}
dataStack.push(x);
}
public void pop() {
if(dataStack.peek().equals(minStack.peek())){
minStack.pop();
}
dataStack.pop();
}
public int top() {
return dataStack.peek();
}
public int getMin() {
return minStack.peek();
}
}
2.单栈解法
使用一个栈既要存放数据又要知道当前栈的最小值
元素A:具体的数据
元素B:最小值
(设计原来栈中存放一个数据的空间现在放两个数据,一个为具体数据,一个为最小值)
class MinStack{
private Stack<Integer> stack ;
public MinStack() {
this.stack = new Stack<>();
}
public void push(int x) {
if(stack.isEmpty()){
stack.push(x);
stack.push(x);
}else{
int temp=stack.peek();
stack.push(x);
if(temp>x){
stack.push(x);
}else{
stack.push(temp);
}
}
}
public void pop() {
stack.pop();
stack.pop();
}
public int top() {
int temp = stack.pop();
int result = stack.peek();
stack.push(temp);
return result;
}
public int getMin() {
return stack.peek();
}
}
由以上2种方法可得单栈解法更好,不管是空间还时间都比双栈好。
测试用例:
public class TestMinStack {
public static void main(String[] args) {
MinStack stack=new MinStack();
stack.push(26);
stack.push(32);
stack.push(12);
stack.push(36);
stack.push(1);
stack.push(60);
System.out.println(stack.getMin());//1
System.out.println(stack.top());//60
stack.pop();
System.out.println(stack.getMin());//1
stack.pop();
System.out.println(stack.getMin());//12
}
}