题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))
题目链接:https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
public class Solution {
private int size;
private int min = Integer.MAX_VALUE;
private Stack<Integer> stack = new Stack<>();
private Integer[] elements = new Integer[10];
public void push(int node) {
ensureCapacity(size+1);
elements[size++] = node;
if (node < min) {
stack.push(node);
min = node;
} else {
stack.push(min);
}
}
private void ensureCapacity(int size) {
int len = elements.length;
if (size > len) {
int newLen = (len * 3) / 2 + 1;
elements = Arrays.copyOf(elements, newLen);
}
}
public void pop() {
Integer top = top();
if (top != null) {
elements[size-1] = null;
size--;
stack.pop();
min = stack.peek();
}
}
public int top() {
if (size != 0) {
if (size - 1 >= 0) {
return elements[size-1];
}
}
return (Integer) null;
}
public int min() {
return min;
}
}