请定义一个队列并实现函数 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;
}
}
这篇博客介绍了一种数据结构设计,通过维护一个双端队列(deque)来实现在常数时间复杂度内获取队列最大值、压入元素以及弹出元素的功能。核心思想是利用辅助队列`helper`作为滑动窗口,始终保持其左端为当前队列的最大值。当新元素大于`helper`队尾元素时,`helper`队列会进行更新,确保最大值始终在队首。这种方法在处理动态数据流并需要高效查询最大值的场景下非常有用。
191

被折叠的 条评论
为什么被折叠?



