LeetCode 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.

Solution 1:

用两个Stack。

class MinStack {
    private Stack<Integer> stack = new Stack<>();
    private Stack<Integer> minStack = new Stack<>();
    
    public void push(int x) {
        stack.push(x);
        if(minStack.isEmpty() || x <= minStack.peek()) {
            minStack.push(x);
        }
    }

    public void pop() {
        int x = stack.pop();
        if(x == minStack.peek()) {
            minStack.pop();
        }
    }

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

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

 

Solution 2:

用一个Stack。

class MinStack {
    private Stack<Long> s = new Stack<Long>();
    private long min;
    
    public void push(int x) {
        if(s.isEmpty()) {
            s.push(0L);
            min = x;
        } else {
            s.push(x-min);
            if(x<min) min=x;
        }
    }

    public void pop() {
        if(s.isEmpty()) return;
        long value = s.pop();
        if(value < 0) {
            min = min - value;
        }
    }

    public int top() {
        long top = s.peek();
        if(top < 0) {
            return (int)min;
        } else {
            return (int)(min + top);
        }
    }

    public int getMin() {
        return (int)min;
    }
}

 

你可能感兴趣的:(LeetCode 155 - Min Stack)