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