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.

Example
push(1)
pop()   // return 1
push(2)
push(3)
min()   // return 2
push(1)
min()   // return 1

分析:
用另一个stack来保存当前最小的值。
 1 public class MinStack<T extends Comparable<T>> {
 2     Stack<T> elements = new Stack<>();
 3     Stack<T> minStack = new Stack<>();
 4     
 5     public MinStack() {
 6         
 7     }
 8     
 9     public void push(T x) {
10         elements.push(x);
11         if (minStack.isEmpty() || x.compareTo(minStack.peek()) <= 0) {
12             minStack.push(x);
13         }
14     }
15     
16     public void pop() { 
17         if (elements.peek().equals(minStack.peek())) {
18             minStack.pop();
19         }
20         elements.pop();
21     }
22     
23     public T top() {
24         return elements.peek();
25     }
26     
27     public T getMin() {
28         return minStack.peek();
29     }
30 }
只用一个stack
 1 class MinStack {
 2     int min = Integer.MAX_VALUE;
 3     Stack<Integer> stack = new Stack<Integer>();
 4     public void push(int x) {
 5         // only push the old minimum value when the current 
 6         // minimum value changes after pushing the new value x
 7         if(x <= min){          
 8             stack.push(min);
 9             min=x;
10         }
11         stack.push(x);
12     }
13 
14     public void pop() {
15         // if pop operation could result in the changing of the current minimum value, 
16         // pop twice and change the current minimum value to the last minimum value.
17         if(stack.pop() == min) min=stack.pop();
18     }
19 
20     public int top() {
21         return stack.peek();
22     }
23 
24     public int getMin() {
25         return min;
26     }
27 }
 
 1 class MinStack {
 2     Stack<Integer> elements = new Stack<>();
 3     Stack<Integer> minStack = new Stack<>();
 4     
 5     public MinStack() {
 6         
 7     }
 8     
 9     public void push(int x) {
10         elements.push(x);
11         if (minStack.isEmpty() || x <= minStack.peek()) {
12             minStack.push(x);
13         }
14     }
15     
16     public void pop() { 
17         if (elements.peek().equals(minStack.peek())) {
18             minStack.pop();
19         }
20         elements.pop();
21     }
22     
23     public int top() {
24         return elements.peek();
25     }
26     
27     public int getMin() {
28         return minStack.peek();
29     }
30 }
31 
32 /**
33  * Your MinStack object will be instantiated and called as such:
34  * MinStack obj = new MinStack();
35  * obj.push(x);
36  * obj.pop();
37  * int param_3 = obj.top();
38  * int param_4 = obj.getMin();
39  */
posted @ 2016-07-09 07:59  北叶青藤  阅读(188)  评论(0)    收藏  举报