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.
Solution:
用两个stack,一个stack用来存储值,一个stack用来维护在当前栈中的最小值。
1 class MinStack { 2 Stack<Integer> vals=new Stack<Integer>(); 3 Stack<Integer> mins=new Stack<Integer>(); 4 public void push(int x) { 5 vals.push(x); 6 if(!mins.isEmpty()){ 7 int temp=mins.peek(); 8 if(temp>=x){ //注意此处!!!在temp=x的时候也要push进去!!!想想[2,0,3,0] 9 mins.push(x); 10 } 11 }else{ 12 mins.push(x); 13 } 14 } 15 16 public void pop() { 17 if(!vals.isEmpty()){ 18 int x=vals.pop(); 19 if(!mins.isEmpty()){ 20 if(x==mins.peek()){ 21 mins.pop(); 22 } 23 }else{ 24 return; 25 } 26 }else{ 27 return; 28 } 29 } 30 31 public int top() { 32 if(!vals.isEmpty()){ 33 return vals.peek(); 34 }else{ 35 return 0; 36 } 37 } 38 39 public int getMin() { 40 if(!mins.isEmpty()){ 41 return mins.peek(); 42 }else{ 43 return 0; 44 } 45 } 46 }