题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
分析:
栈s1用来执行正常的压入弹出操作,栈s2用来存储最小的值。即只有当栈s2为空或者新压入的数据比s2栈顶的元素小时,才将数据压入s2;执行弹出操作时,当s1和s2栈顶元素相同时,才将s2栈顶元素弹出。最后s2栈顶的元素始终为最小值。
import java.util.Stack;
public class Solution {
private Stack<Integer> s1 = new Stack<Integer>();
private Stack<Integer> s2 = new Stack<Integer>();
public void push(int node) {
s1.push(node);
if(s2.empty() || s2.peek() > node)
s2.push(node);
}
public void pop() {
if(s1.peek() == s2.peek())
s2.pop();
s1.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.peek();
}
}