offer-59-2


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

若队列为空,pop_frontmax_value 需要返回 -1

示例 1:

输入: 
["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]

示例 2:

输入: 
["MaxQueue","pop_front","max_value"]
[[],[],[]]
输出: [null,-1,-1]

限制:

  • 1 <= push_back,pop_front,max_value的总操作数 <= 10000
  • 1 <= value <= 10^5

//leetcode submit region begin(Prohibit modification and deletion)
class MaxQueue {

    private int maxValue;
    private Queue<Integer> thisQueue;

    public MaxQueue() {
        maxValue = Integer.MIN_VALUE;
        thisQueue = new LinkedList<>();
    }

    public int max_value() {
        if (thisQueue.isEmpty()) {
            return -1;
        }
        return maxValue;
    }

    public void push_back(int value) {
        if (value > maxValue) {
            maxValue = value;
        }
        thisQueue.add(value);
    }

    public int pop_front() {
        if (thisQueue.isEmpty()) {
            return -1;
        }
        int polled = thisQueue.poll();
        if (polled == maxValue) {
            maxValue = Integer.MIN_VALUE;
            for (int value : thisQueue) {
                if (value > maxValue) {
                    maxValue = value;
                }
            }
        }
        return polled;
    }
}

/**
 * Your MaxQueue object will be instantiated and called as such:
 * MaxQueue obj = new MaxQueue();
 * int param_1 = obj.max_value();
 * obj.push_back(value);
 * int param_3 = obj.pop_front();
 */
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !