题目
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min,push及pop的时间复杂度都是O(1)。
解
import java.util.Stack;
public class StackWithMin {
Stack<Integer> m_data=new Stack<Integer>();//数据栈
Stack<Integer> m_min=new Stack<Integer>();//辅助栈,用来存储当前数据集对应的最小元素
void push(Integer value){
m_data.push(value);
if(m_min.size()==0||value<m_min.peek()){
m_min.push(value);
}else{
m_min.push(m_min.peek());
}
}
void pop(){
if(m_min.size()>0 && m_data.size()>0){
m_data.pop();
m_min.pop();
}
}
Integer min(){
if(m_min.size()>0 && m_data.size()>0){
return m_min.peek();
}else{
return null;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
本文介绍了一种特殊的数据结构——带有min函数的栈,该栈能够在常数时间内完成push、pop和min操作。通过使用两个栈,一个用于存储数据,另一个用于跟踪最小值,实现了高效的栈操作。
1907

被折叠的 条评论
为什么被折叠?



