分析
难度 易
来源
https://leetcode.com/problems/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 package LeetCode; 2 3 import java.util.LinkedList; 4 import java.util.Stack; 5 6 /** 7 * Your MinStack object will be instantiated and called as such: 8 * MinStack obj = new MinStack(); 9 * obj.push(x); 10 * obj.pop(); 11 * int param_3 = obj.top(); 12 * int param_4 = obj.getMin(); 13 */ 14 public class L155_MinStack { 15 /* private LinkedList<Integer> stack=null; 16 int min=Integer.MAX_VALUE; 17 public L155_MinStack() { 18 stack=new LinkedList<Integer>(); 19 } 20 21 public void push(int x) { 22 if(x<=min){ 23 stack.addLast(min);//把之前的min压栈 24 min=x; 25 } 26 stack.addLast(x); 27 } 28 29 public void pop() { 30 if(min==stack.removeLast()) 31 min=stack.removeLast(); 32 } 33 34 public int top() { 35 return stack.getLast(); 36 } 37 38 public int getMin() { 39 return min; 40 }*/ 41 //数组实现 42 /*实时改变min 43 Runtime: 76 ms, faster than 46.13% of Java online submissions for Min Stack. 44 */ 45 /* private Integer[] stack=null; 46 private int maxSize=10000; 47 private int top=-1; 48 int min=Integer.MAX_VALUE; 49 public L155_MinStack() { 50 stack=new Integer[maxSize]; 51 } 52 53 public void push(int x) { 54 if(top==maxSize-1){//栈满 55 maxSize*=2; 56 Integer[] temp=stack; 57 stack=new Integer[maxSize]; 58 for(int i=0;i<temp.length;i++){ 59 stack[i]=temp[i]; 60 } 61 } 62 stack[++top]=x; 63 if(stack[top]<min) 64 min=stack[top]; 65 } 66 67 public void pop() { 68 if(stack[top]==min){ 69 min=Integer.MAX_VALUE; 70 for(int i=0;i<top;i++) 71 { 72 if(stack[i]<min) 73 min=stack[i]; 74 } 75 } 76 top--; 77 } 78 79 public int top() { 80 return stack[top]; 81 } 82 83 public int getMin() { 84 return min; 85 }*/ 86 /*注意最小值的保存,否则后边没法求min 87 使用java的stack 88 */ 89 private Stack<Integer> stack=null; 90 int min=Integer.MAX_VALUE; 91 public L155_MinStack() { 92 stack=new Stack<Integer>(); 93 } 94 95 public void push(int x) {//int比Integer快好多啊 96 if(x<=min){ 97 stack.push(min);//把之前的min压栈 98 min=x; 99 } 100 stack.push(x); 101 } 102 103 public void pop() { 104 if(min==stack.pop())//当前栈顶数字等于最小值,栈顶出栈,最小数字为下方数字,栈顶入栈前的最小数字。不管等不等,pop操作都执行过了 105 min=stack.pop();//把最小值出栈,余下正常栈顶 106 } 107 108 public int top() { 109 return stack.peek(); 110 } 111 112 public int getMin() { 113 return min; 114 } 115 }
博客园的编辑器没有CSDN的编辑器高大上啊