首页 > 其他 > 详细

Min Stack

时间:2014-11-10 17:09:41      阅读:238      评论:0      收藏:0      [点我收藏+]

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.
 1 class MinStack {
 2         List<Integer> stack = new ArrayList<Integer>();
 3     int top = -1;
 4     int min = Integer.MAX_VALUE;
 5 
 6     public void push(int x) {
 7         top++;
 8         stack.add(x);
 9         if(min > x){
10             min = x;
11         
12         }
13             
14     }
15 
16     public void pop() {
17 
18         int element = stack.remove(top--);
19         if(element == min)
20         {            
21                 updateMin();            
22                 
23         }
24     }
25 
26     public int top() {
27         int result = stack.get(top);
28       
29         return result;
30     }
31 
32     public int getMin() {
33         
34         return this.min;
35     }
36     public void updateMin(){
37         if(top == -1)
38         {
39             min = Integer.MAX_VALUE;        
40             return;
41         }
42         min = stack.get(0);
43         for(int i = 1; i <= top; i++){
44             if(min > stack.get(i))
45                 min = stack.get(i);
46         }
47     }
48 }

 

Min Stack

原文:http://www.cnblogs.com/luckygxf/p/4087199.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!