Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

我用了两个栈

不知道有没有更好的方法

class MinStack {

    Stack<Integer> st = new Stack<Integer>();

    Stack<Integer> min = new Stack<Integer>();

    public void push(int x) {

        st.push(x);

        if(min.isEmpty()){

            min.push(x);

        }else{

            if(x<=min.peek())

                min.push(x);

        }

    }



    public void pop() {

        int tmp = st.peek();

        st.pop();

        if(tmp==min.peek())

            min.pop();

    }



    public int top() {

        return st.peek();

    }



    public int getMin() {

        return min.peek();

    }

}

 

你可能感兴趣的:(stack)