Min Stack

lc 155. 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.

two stacks solutions


  private Stack<Integer> stack = new Stack<Integer>();
   private Stack<Integer> minstack = new Stack<Integer>();
    public MinStack() {
        Stack<Integer> stack = new Stack<Integer>();
        Stack<Integer> minstack = new Stack<Integer>();
    }

    public void push(int x) {

        stack.push(x);
        if (minstack.empty()){
            minstack.push(x);
        }else{
            minstack.push(Math.min(minstack.peek(), x));
        }
    }

    public void pop() {
        if (stack.empty()) return;
        stack.pop();
        minstack.pop();
    }

    public int top() {
       return stack.peek();
    }

    public int getMin() {
        return minstack.peek();
    }

one statck solution

public class MinStack {

private Stack<Integer> stack = new Stack<Integer>();
int min = Integer.MAX_VALUE;

    public void push(int x) {
        if( x <= min){
            stack.push(min);
            min = x;
        }

        stack.push(x);
    }

    public void pop() {
        if(stack.peek() == min){
            stack.pop();
            min = stack.pop();
        }else{
            stack.pop();
        }
    }

    public int top() {
       return stack.peek();
    }

    public int getMin() {
        return min;
    }

}

results matching ""

    No results matching ""