Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack
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(); } }
时间: 2024-09-28 20:04:05