首页 > 其他 > 详细

Min Stack

时间:2017-02-14 12:21:00      阅读: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.

 Notice

min operation will never be called if there is no number in the stack.

分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class MinStack {
    private Stack<Integer> stack = new Stack<Integer>();
    private Stack<Integer> stack_min = new Stack<Integer>();
     
    public MinStack() {
        // do initialize if necessary
    }
     
    public void push(int number) {
        // write your code here
        stack.push(number);
        if(!stack_min.empty() && stack_min.peek() < number){
            stack_min.push(stack_min.peek());
        }
        else{
            stack_min.push(number);
        }
    }
 
    public int pop() {
        // write your code here
        int top = -1;
        if(!stack.empty()){
            top = stack.peek();
            stack.pop();
            stack_min.pop();
        }
        return top;
    }
 
    public int min() {
        // write your code here
        return stack_min.empty() ? -1 : stack_min.peek();
    }
}




Min Stack

原文:http://www.cnblogs.com/zhxshseu/p/de52b1cfc3c013858c635bafd7423fd1.html

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