首页 > 其他 > 详细

LintCode MinStack

时间:2016-08-25 23:47:33      阅读:272      评论:0      收藏:0      [点我收藏+]

Implement a stack with min() function, which will return the smallest number in the stack.

It should support push, pop and min operation all in O(1) cost.

Example

push(1)
pop()   // return 1
push(2)
push(3)
min()   // return 2
push(1)
min()   // return 1


 1 public class MinStack {
 2     private Stack<Integer> minStack;
 3     private Stack<Integer> stack;
 4     public MinStack() {
 5         // do initialize if necessary
 6         minStack = new Stack<Integer>();
 7         stack = new Stack<Integer>();
 8     }
 9 
10     public void push(int number) {
11         // write your code here
12         stack.push(number);
13         if (minStack.isEmpty()) {
14             minStack.push(number);
15         } else {
16             if(number <= minStack.peek()) {
17                 minStack.push(number);
18             }
19         }
20     }
21 
22     public int pop() {
23         // write your code here
24         //here you use equals which stand for two peeked values
25         //need to be exactly same.
26         //If they are both null, it also works
27         if (stack.peek().equals(minStack.peek())) {
28             minStack.pop();
29         }
30         return stack.pop();
31     }
32 
33     public int min() {
34         // write your code here
35         return minStack.peek();
36     }
37 }

In this problem, we want to get the current smallest value and implemnt a stack. The main issue is to get current smallest value. So we should use another stack to remember the current smallest values and delete them when we pop that value out.

 

Trcks: Use stack.peek().equals(minStack.peek()) instead of stack.peek() == minStack.peek() becuase peek() method could return null value and if they are both null it is also okay.

 

LintCode MinStack

原文:http://www.cnblogs.com/ly91417/p/5808567.html

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