[LeetCode] 155. Min Stack

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

  • MinStack() initializes the stack object.
  • void push(int val) pushes the element val onto the stack.
  • void pop() removes the element on the top of the stack.
  • int top() gets the top element of the stack.
  • int getMin() retrieves the minimum element in the stack.

Example1:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

这道题因为想要getMin也是O(1)的操作,所以遍历的话就会是O(N). 所以可以用两个stack,一个用来记住数据,一个用来记住最小值。当一个数据来的时候,先加入到数据的stack,然后再和最小值stack里最上面的值做比较,要是比最上面的值小,就把这个值也加入到最小值的stack里,如果比最小值最上面的stack大,那么就把最小值最上面的值重复加入到最小值stack里。这样做可以保证两个stack的size相等,同时每个数据stack所处的位置的最小值,都是被记录在相同最小值stack里的相同位置上。当需要删除数据的时候,要两个同步删除。
注意:

  • 最小值因为开始stack是空的,所以不能直接调用peek,要先判断一下是否为空。
  • 写class的时候,先要声明变量,然后再构造函数里初始化。
class MinStack {
    
     Stack<Integer> input;
     Stack<Integer> min;
    
    public MinStack() {
        input = new Stack<Integer>();
        min = new Stack<Integer>();
    }
    
    public void push(int val) {
        input.push(val);
        if (this.min.size() > 0 && min.peek() < val) {
            min.push(min.peek());
        } else {
            min.push(val);
        }
    }
    
    public void pop() {
        input.pop();
        min.pop();
    }
    
    public int top() {
        return input.peek();
    }
    
    public int getMin() {
        return min.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

posted on 2022-01-16 08:04  codingEskimo  阅读(20)  评论(0编辑  收藏  举报

导航