题目
https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/
解题思路
使用一个双向链表辅助,保存最大值序列
Note:链表中小于后插入的元素的元素,对结果没有影响
代码
class MaxQueue {
private:
queue<int> que;
list<int> que_vice;
public:
MaxQueue() {
}
int max_value() {
// cout<<"max:"<<que_vice.front()<<endl;
if(que.empty()){
return -1;
}
return que_vice.front();
}
void push_back(int value) {
// cout<<"pus:"<<value<<endl;
if(value > que_vice.front()){ // 大于最大元素
que_vice.clear();
que_vice.push_back(value);
}else{
// 移除所有小于当前插入元素的结点
while(que_vice.back() < value){
que_vice.pop_back();
}
que_vice.push_back(value);
}
que.push(value);
}
int pop_front() {
if(que.empty()){
return -1;
}
int t = que.front();
que.pop();
if(t == que_vice.front()){
que_vice.pop_front();
}
// cout<<"pop:"<<t<<endl;
return t;
}
};
/**
* 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面试题59 - II.队列的最大值问题。通过维护一个保存最大值序列的链表,该算法确保了快速获取队列的最大值,并在插入和删除操作中保持O(1)的时间复杂度。
290





