标签:des style blog color sp div on log bs
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
1, 记得stack的几个函数,isEmpty(),不能用null, equals,还有读stack最上面的数,但是不取出来的peek()
2,解法,用另外一个stack来计算最小的,最上面的永远是最小的
class MinStack { Stack<Integer> sta=new Stack<Integer>(); Stack<Integer> minsta=new Stack<Integer>(); public void push(int x) { sta.push(x); if(minsta.isEmpty()||x<=minsta.peek()){ minsta.push(x); } } public void pop() { if(sta.peek().equals(minsta.peek())){ minsta.pop(); } sta.pop(); } public int top() { return sta.peek(); } public int getMin() { return minsta.peek(); } }
标签:des style blog color sp div on log bs
原文地址:http://www.cnblogs.com/lilyfindjobs/p/4088620.html