定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
题解:需要一个辅助栈
import java.util.Stack;
public class Solution {
Stack<Integer> m_data = new Stack<Integer>();
Stack<Integer> m_min = new Stack<Integer>();
public void push(int node) {
m_data.push(node);
if(m_min.empty()){
m_min.push(node);
}else{
if(node <= m_min.peek()){
m_min.push(node);
}else{
m_min.push(m_min.peek());
}
}
}
public void pop() {
m_data.pop();
m_min.pop();
}
public int top() {
return m_data.peek();
}
public int min() {
return m_min.peek();
}
}