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

Min Stack

时间:2017-01-10 10:13:00      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:ret   style   div   called   实现   strong   log   function   return   

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.

Example

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

 

这道题也没什么好说的,只是要想到用两个stack实现,还要注意比较较的时候用equals比较好一点。

另外,比较的时候要有等号,如果都是最小值,要放多次。

public class MinStack {
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    public MinStack() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void push(int number) {
        if (stack1.isEmpty()) {
            stack1.push(number);
        } else if (number <= stack1.peek()) {
            stack1.push(number);
        }
        stack2.push(number);
    }

    public int pop() {
        int tmp = stack2.pop();
        if (stack1.peek().equals(tmp)) {
            stack1.pop();
        }
        return tmp;
    }

    public int min() {
        return stack1.peek();
    }
}

 

Min Stack

标签:ret   style   div   called   实现   strong   log   function   return   

原文地址:http://www.cnblogs.com/aprilyang/p/6268053.html

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