美文网首页
155. Min Stack

155. Min Stack

作者: CharlieGuo | 来源:发表于2018-07-31 23:57 被阅读0次

    Description:

    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.

    Example:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> Returns -3.
    minStack.pop();
    minStack.top();      --> Returns 0.
    minStack.getMin();   --> Returns -2.
    

    Solutions:

    Approach: Use two stacks

    用两个栈,一个栈stackData用作普通的栈存放数据,一个栈stackMin只存放当前最小的值。
    注意两点

    1. 如果当前入栈的数等于stackMin栈顶的数,则该数两个栈都要压入。弹栈时,若两个栈顶的数大小相同,则都弹出。
    2. 比较栈顶的数时不能用等于号(==),因为栈内元素为包装过的Integer对象,若要比较要通过intValue()方法获取int值后再比较。
      代码如下:
    import java.util.Stack;
    class MinStack {
    
        /** initialize your data structure here. */
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;
        public MinStack() {
            stackData = new Stack<Integer>();
            stackMin = new Stack<Integer>();
        }
        
        public void push(int x) {
            if (stackData.isEmpty() || x <= stackMin.peek()) {
                stackMin.push(x);
            }
                stackData.push(x);
        }
        
        public void pop() {
            if (stackData.isEmpty()) {
                return;
            }
            int val = stackData.pop();
            if (stackMin.peek().intValue() == val) {
                stackMin.pop();
            } 
        }
        
        public int top() {
            return stackData.peek();
        }
        
        public int getMin() {
            return stackMin.peek();
        }
    }
    

    相关文章

      网友评论

          本文标题:155. Min Stack

          本文链接:https://www.haomeiwen.com/subject/unwkvftx.html