请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_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]
思路:使用滑动窗口
class MaxQueue { //放置数据 private LinkedList<Integer> data; //保持队列的最左端为当前的最大值。滑动窗口 private LinkedList<Integer> helper; public MaxQueue() { data = new LinkedList<>(); helper = new LinkedList<>(); } public int max_value() { //取滑动窗口最左端的数据 if (!helper.isEmpty()) { return helper.peekFirst(); } return -1; } public void push_back(int value) { data.offer(value); if (helper.isEmpty()) { helper.offer(value); } else { //保持队列的最左端为当前的最大值 Integer last = helper.peekLast(); while (last <= value && !helper.isEmpty()) { helper.pollLast(); if (!helper.isEmpty()) { last = helper.peekLast(); } } helper.offer(value); } } public int pop_front() { if (!data.isEmpty()) { int r = data.pollFirst(); int max = helper.peekFirst(); //保持队列的最左端为当前的最大值 if (max == r) { helper.pollFirst(); } return r; } return -1; } }