Min Stack
Implement a stack with min() function, which will return the smallest number in the stack.
It should support push, pop and min operation all in O(1) cost.
Notice
min operation will never be called if there is no number in the stack.
min operation will never be called if there is no number in the stack.
分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | public class MinStack { private Stack<Integer> stack = new Stack<Integer>(); private Stack<Integer> stack_min = new Stack<Integer>(); public MinStack() { // do initialize if necessary } public void push( int number) { // write your code here stack.push(number); if (!stack_min.empty() && stack_min.peek() < number){ stack_min.push(stack_min.peek()); } else { stack_min.push(number); } } public int pop() { // write your code here int top = - 1 ; if (!stack.empty()){ top = stack.peek(); stack.pop(); stack_min.pop(); } return top; } public int min() { // write your code here return stack_min.empty() ? - 1 : stack_min.peek(); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步