码迷,mamicode.com
首页 > 其他好文 > 详细

Min Stack

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

标签:des   style   blog   io   color   ar   sp   for   div   

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

标签:des   style   blog   io   color   ar   sp   for   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!