原题链接:https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/

deque<int> Q1;
deque<int> Q2;
MaxQueue() {
}
int max_value() {
if (Q1.empty()) return -1;
return Q2.front();
}
void push_back(int value) {
Q1.push_back(value);
while (!Q2.empty() && Q2.back() < value) {
Q2.pop_back();
}
Q2.push_back(value);
}
int pop_front() {
if (Q1.empty()) return -1;
if (!Q2.empty() && Q2.front() == Q1.front()) Q2.pop_front();
int t = Q1.front();
Q1.pop_front();
return t;
}
type MaxQueue struct {
data []int
ma []int
}
func Constructor() MaxQueue {
return MaxQueue{
data: make([]int, 0),
ma: make([]int, 0),
}
}
func (this *MaxQueue) Max_value() int {
if len(this.ma) == 0 {
return -1
}
return this.ma[0]
}
func (this *MaxQueue) Push_back(value int) {
for len(this.ma) != 0 && this.ma[len(this.ma)-1] < value {
this.ma = this.ma[:len(this.ma)-1]
}
this.data = append(this.data, value)
this.ma = append(this.ma, value)
}
func (this *MaxQueue) Pop_front() int { if len(this.data) <= 0 { return -1 }
d := this.data[0]
this.data = this.data[1:]
if d == this.ma[0] {
this.ma = this.ma[1:]
}
return d
}
该博客讨论了如何设计并实现一个名为MaxQueue的数据结构,它结合了队列和最大值堆的功能。MaxQueue提供了max_value()方法来获取当前队列中的最大值,push_back()方法用于在队尾插入元素,以及pop_front()方法删除队头元素。代码使用双端队列(deque)作为基础,并通过维护一个小顶堆(max heap)来快速获取最大值。

333

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



