题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
解题思路
这个题目感觉就是要求读懂题意。题目默认可以使用系统的栈方法,实现一个能够得到栈最小元素的min函数,要求复杂度为O(1)。
使用stack1作为主栈,stack2作为辅助栈保存最小值。当stack1中新加入的值比stack2中的还要小,压入stack2。pop的时候比对一下stack1和stack2栈顶的值,一样的话,stack2中的值也要pop。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
if(stack2.empty())
stack2.push(node);
else if(node<stack2.peek())
stack2.push(node);
}
public void pop() {
if(stack2.peek()==stack1.peek())
stack2.pop();
stack1.pop();
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}