1 题目

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.

2 思路

前三个直接调用系统函数即可。c++之类还需要思考一下越界之类的问题。主要实现的是getMin(),要求在常数时间内实现,想了一下,没想出来,搜索,发现可以用空间换时间,新建个最小数的stack就可以了,要注意push时条件是等号。

3 代码

    private Stack<Integer> stack = new Stack<Integer>();
    private Stack<Integer> min_stack = new Stack<Integer>();
    public void push(int x) {
        if (stack.isEmpty()) {
            min_stack.push(x);
        }else {
            if (x <= min_stack.peek()) {//小于等于
                min_stack.push(x);
            }
        }
        stack.push(x);
    }

    public void pop() {
        int x = stack.pop();
       if (x == min_stack.peek()) {//相等
        min_stack.pop();
    } 
    }

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

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