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

[Leetcode] Min Stack

时间:2014-12-30 06:59:26      阅读:131      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!