题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
import java.util.Stack;
public class Solution {
Stack<Integer> stack = new Stack<>();
Stack<Integer> temp = new Stack<>();
int min = Integer.MAX_VALUE;
public void push(int node) {
if(node < min){
min = node;
stack.push(node);
temp.push(node);
}else{
stack.push(node);
temp.push(min);
}
}
public void pop() {
stack.pop();
temp.pop();
}
public int top() {
int t = stack.pop();
stack.push(t);
return t;
}
public int min() {
int t = temp.pop();
temp.push(t);
return t;
}
}