Min Stack

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();
    }
}

 

posted @ 2017-01-10 06:37  璨璨要好好学习  阅读(120)  评论(0编辑  收藏  举报