155. Min Stack

两个stack,一个存正常的数,一个存min值,重点在于,如果有和当前最小值一样的新的数进来,也要推进min stack

 1 public class MinStack {
 2     Stack<Integer> stack;
 3     Stack<Integer> min;
 4 
 5     /** initialize your data structure here. */
 6     public MinStack() {
 7         stack = new Stack<Integer>();
 8         min = new Stack<Integer>();
 9     }
10     
11     public void push(int x) {
12         if(min.isEmpty() || x <= min.peek()) {
13             min.push(x);
14         }
15         stack.push(x);
16     }
17     
18     public void pop() {
19         if(!min.isEmpty()) {
20             int curMin = min.peek();
21             int cur = stack.pop();
22             if(curMin == cur) {
23                 min.pop();
24             }
25         }
26     }
27     
28     public int top() {
29         return stack.peek();
30     }
31     
32     public int getMin() {
33         return min.peek();
34     }
35 }

 

posted @ 2016-06-21 09:08  warmland  阅读(87)  评论(0编辑  收藏  举报