首页 > 其他 > 详细

[Leetcode] Min Stack

时间:2014-12-30 06:57:52      阅读:277      评论:0      收藏:0      [点我收藏+]

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     }

 

[Leetcode] Min Stack

原文:http://www.cnblogs.com/Phoebe815/p/4192769.html

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