剑指 Offer 30. 包含min函数的栈

剑指 Offer 30. 包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

思路

开一个栈用来做 push, pop,再开另外一个辅助栈用来维护 min 值

待填坑:还有不用辅助栈的做法

代码

class MinStack {

    /** initialize your data structure here. */
    Deque<Integer> stack;
    Deque<Integer> minStack;
    public MinStack() {
        stack = new LinkedList<Integer>();
        minStack = new LinkedList<Integer>();
        minStack.push(Integer.MAX_VALUE);
    }

    
    public void push(int x) {
        stack.push(x);
        minStack.push(Math.min(minStack.peek(), x));
    }

    public void pop() {
        stack.pop();
        minStack.pop();

    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        return minStack.peek();
    }
}
posted @ 2022-04-14 16:24  沐灵_hh  阅读(19)  评论(0编辑  收藏  举报