Leetcode-队列得最大值
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。若队列为空,pop_front 和 max_value 需要返回 -1
O(1) 复杂度,意味着min值需要采取特殊手段:双端队列:
- 当push的值大于队尾元素,则pop掉队列中比这个值大的元素,再把这个元素入队
- 否则,直接入队
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <climits>
using namespace std;
/*
tail = 0,head=0,max_size;
push:
pop:
empty:
full:
*/
class Dequque{
private:
int *data;
int max_size;
int head_loc;
int tail_loc;
public:
Dequque();
void push(const int value);
void pop_back();
void pop_front();
int front();
int tail();
bool empty();
bool full();
};
Dequque::Dequque(){
max_size = 10000;
head_loc = 0;
tail_loc = 0;
data = new int[max_size];
}
void Dequque::push(const int value){
if(full())
std::cerr<<"full, cant push"<<endl;
data[tail_loc] = value;
tail_loc = (tail_loc+1) % max_size;
}
void Dequque::pop_back(){
if(empty())
std::cerr<<"empty, cant pop back"<<endl;
tail_loc = (tail_loc-1) % max_size;
}
void Dequque::pop_front(){
if(empty())
std::cerr<<"empty, cant pop front"<<endl;
head_loc = (head_loc+1) % max_size;
}
int Dequque::front(){
if(!empty())
return data[head_loc];
return -1;
}
int Dequque::tail(){
if(!empty())
return data[tail_loc-1];
return -1;
}
bool Dequque::empty(){
return head_loc==tail_loc;
}
bool Dequque::full(){
return (tail_loc+1) % max_size == head_loc;
}
class MaxQueue {
private:
int *data;
int max_size;
int head;
int tail;
Dequque dequeue;
public:
MaxQueue() {
data = new int[10000];
max_size = 10000;
head = 0;
tail = 0;
}
int max_value_slow(){
int max_val = INT_MIN;
if(head==tail)
return -1;
for(int i=head;i<=tail;i++)
max_val = max(max_val, data[i]);
return max_val;
}
int max_value(){
if(!dequeue.empty())
return dequeue.front();
return -1;
}
void push_back(int value) {
data[tail] = value;
tail = (tail+1)%max_size;
if(dequeue.empty() || dequeue.tail()>value)
dequeue.push(value);
else{
while(!dequeue.empty() && dequeue.tail()<value)
dequeue.pop_back();
dequeue.push(value);
}
}
int pop_front(){
if(empty())
return -1;
int val = front();
head = (head+1)%max_size;
if(val==dequeue.front())
dequeue.pop_front();
return val;
}
int front(){
if(!empty())
return data[head];
else
return -1;
}
bool empty(){
return head==tail;
}
};