题目
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
分析:
使用两个栈;一个栈用来保存最小值,一个栈用来正常存储操作。
保存最小值的栈,每次在push操作时,都会将最小值同步压入。
代码实现
import java.util.Stack;
public class Solution {
Stack<Integer> CurStack = new Stack<>();
Stack<Integer> MinStack = new Stack<>();
public void push(int node) {
if(this.MinStack.isEmpty()){
this.MinStack.push(node);
}else if(node < this.MinStack.peek()){
this.MinStack.push(node);
}else{
this.MinStack.push(this.MinStack.peek());
}
this.CurStack.push(node);
}
public void pop() {
if(this.CurStack.isEmpty()){
throw new RuntimeException("The stack is empty");
}
this.MinStack.pop();
this.CurStack.pop();
}
public int top() {
if(this.CurStack.isEmpty()){
throw new RuntimeException("The stack is empty");
}
return this.CurStack.peek();
}
public int min() {
if(this.CurStack.isEmpty()){
throw new RuntimeException("The stack is empty");
}
return this.MinStack.peek();
}
}