[LeetCode] Min Stack

Question:

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.

1、题型分类:

2、思路:

  这道题需要实现一个能够获取最小值的栈,可以想到的必然是要么每次通过遍历获取,要么空间换时间,新建一个数据结构存储这些有序最小值。刚开始一直没有想过用Stack去实现这个功能,想到的是利用List去进行有序存储,但是这样每次插入的时间复杂度都不低,另外还有删除操作,没法实现题目的要求。现在希望一个数据结构,数据有序且从顶至下由小到大且能够包含所有的元素,这样就能够与Stack并行操作了,但是实现想不出来这样的结构。再去考虑这道题目的关键,getMin获取最小值,但不需要删除,那么我们可以存储插入进来的小于当前最小值的数值,,而且这个顺序还必须和Stack里面数的顺序一致,那么最后还是需要使用Stack,问题来了,删除怎么办?由于顺序一致,只要两个栈顶部数据相同就删除。如下图:

  

3、时间复杂度:

4、代码:

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

    public void pop() {
        if(!stack.isEmpty())
        {
            if(!minStack.isEmpty() && minStack.peek().intValue()==stack.peek().intValue())
                minStack.pop();
            stack.pop();
        }
    }

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

    public int getMin() {
        if(!minStack.isEmpty())
            return minStack.peek();
        return 0;
    }
}

5、优化:

6、扩展:

原文地址:https://www.cnblogs.com/maydow/p/4644513.html