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.

分析:

逻辑本身不复杂,只要注意更新minVal的方法就可以

解法:

public class MinStack {
    public Stack<Integer> stackRegular, stackMin;
    public int minVal;

    public MinStack() {
        // do initialize if necessary
        stackRegular = new Stack<Integer>();
        stackMin = new Stack<Integer>();
        minVal = Integer.MAX_VALUE;
    }

    public void push(int number) {
        // write your code here
        stackRegular.push(number);
        if (number < minVal) {
            minVal = number;
        }
        stackMin.push(minVal);
    }

    public int pop() {
        // write your code here
        int res = -1;
        if (!stackRegular.empty() ) {
            res = stackRegular.peek();
            stackRegular.pop();
            stackMin.pop();

            minVal = stackMin.empty() ? Integer.MAX_VALUE : stackMin.peek();
        } 
        return res;
    }

    public int min() {
        // write your code here
        int res = -1;
        if (!stackMin.empty() ) {
            res = stackMin.peek();
        }
        return res;
    }
}

results matching ""

    No results matching ""