LeetCode-155. Min Stack
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.
Example:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
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 36 37 38 39 40 41 42 43 44 | class MinStack { // 栈 my List<Integer> list ; int num; int min; /** initialize your data structure here. */ public MinStack() { list= new ArrayList<Integer>(); num = 0 ; min=Integer.MAX_VALUE; } public void push( int x) { list.add(x); num++; if (min>x){ min=x; } } public void pop() { if ( 0 <num){ if (min == list.get(num- 1 )){ min=Integer.MAX_VALUE; for ( int i = 0 ; i < num- 1 ; i++) { if (min>list.get(i)){ min=list.get(i); } } } list.remove(num- 1 ); num--; } } public int top() { return num> 0 ?list.get(num- 1 ): 0 ; } public int getMin() { return min; } } |
时间复杂度为O(1)的解法
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 36 37 38 39 40 41 42 | class MinStack { Stack<Integer> minStack ; Stack<Integer> stack; int min=Integer.MAX_VALUE; /** initialize your data structure here. */ public MinStack() { stack= new Stack<Integer>(); minStack = new Stack<Integer>(); min=Integer.MAX_VALUE; } public void push( int x) { stack.push(x); if (min>x){ min=x; } minStack.push(min); } public void pop() { if (!stack.isEmpty()){ minStack.pop(); stack.pop(); } if (stack.isEmpty()){ min = Integer.MAX_VALUE; } else { min = minStack.peek(); } } public int top() { return stack.peek(); } public int getMin() { return min; } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步