题目链接
Leecode 面试题59-2
题目要求:
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
分析:
采取两个队列,一个普通队列保存顺序入队的数,一个双端队列按单调递减保存队列值。 队列不空时,max_value函数返回双端队列的队首元素。 push_back在插入新元素到普通队列时,双端队列需要比较插入值与队列元素,将比插入值小的元素从尾部出队,直到队尾元素不小于插入值,插入值从队尾入队。 pop_front 在出队普通队列队首元素时,如果出队值同时为双端队列队首元素(即最大值),需要将该元素同时从双端队列出队。
采取空间换时间的方式。
代码
class MaxQueue {
int queue[20000];
int sort[20000];
int qbegin = 0, qend = 0;
int sbegin = 0, send = 0;
public:
MaxQueue() {
}
int max_value() {
if(sbegin==send) return -1;
return sort[sbegin+1];
}
void push_back(int value) {
while(sbegin!=send && sort[send]<value){
send--;
}
sort[++send] = value;
queue[++qend] = value;
}
int pop_front() {
if(qbegin == qend) return -1;
int qfront = queue[qbegin+1];
if(qfront == sort[sbegin+1]){
sbegin++;
}
qbegin++;
return qfront;
}
};