其他分享
首页 > 其他分享> > 剑指offer_30_包含min函数的栈_单调栈 / 数据结构

剑指offer_30_包含min函数的栈_单调栈 / 数据结构

作者:互联网

很经典的一道题,如果没做过,我感觉还是挺难想的。题解是用了单调栈作为辅助栈。
其实仔细看这道题,要求push和pop都是O1,所以还是必须得用栈,无非多要求了个min,我们将每层的min存进去就好了其实。

class MinStack {
    Deque<int[]> deque = new ArrayDeque<>();

    /** initialize your data structure here. */
    public MinStack() {

    }

    public void push(int x) {
        deque.push(new int[]{x, Math.min(x, deque.isEmpty() ? x : deque.peek()[1])});
    }

    public void pop() {
        deque.pop();
    }

    public int top() {
        return deque.peek()[0];
    }

    public int min() {
        return deque.peek()[1];
    }
}

标签:deque,offer,int,30,pop,min,peek,public
来源: https://blog.csdn.net/HDUCheater/article/details/122769923