title: '算法:包含min函数的栈' cover: https://img.paulzzh.com/touhou/random?29 categories: 算法题目 toc: true date: 1996-07-27 08:00:00
<br/>
<!--more-->定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
设定两个栈stack和minStack
由于以上两点, 保证了minStack.peak即为当前栈中的min
import java.util.Stack;
public class Solution {
private static Stack<Integer> stack;
private static Stack<Integer> minStack;
static {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int node) {
stack.push(node);
if (minStack.isEmpty() || node <= minStack.peek()) {
minStack.push(node);
}
}
public void pop() {
if (stack.peek() == minStack.peek()) {
minStack.pop();
}
stack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return minStack.peek();
}
}