跳至主要內容

59(2)-队列的最大值

daipeng小于 1 分钟

请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。

若队列为空,pop_front 和 max_value 需要返回 -1

    private Queue<Integer> data = new LinkedList<>();
    private Deque<Integer> aux = new LinkedList<>();

    public int max_value() {
        if (aux.isEmpty()) {
            return -1;
        }
        return aux.peekFirst();
    }

    public void push_back(int value) {
        data.add(value);
        while(!aux.isEmpty() && aux.peekLast() < value){
            aux.pollLast();
        }
        aux.add(value);
    }

    public int pop_front() {
        if (data.isEmpty()) {
            return -1;
        }else{
            if (aux.peekFirst().equals(data.peek())) {
                aux.pollFirst();
            }
            return data.poll();
        }
    }