题目
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
 
思路
对于一个普通队列,push_back 和 pop_front 的时间复杂度都是 O(1),因此直接使用队列的相关操作就可以实现这两个函数。
但是对于 max_value 函数,通常会这样思考,即每次入队操作时都更新最大值,但是当出队时,这个方法会造成信息丢失,即当最大值出队后,无法知道队列里的下一个最大值。
针对这个问题,可以采用双端队列解决:具体方法是使用一个双端队列 deque,在每次入队时,如果 deque 队尾元素小于即将入队的元素 value,则将小于 value 的元素全部出队后,再将 value入队;否则直接入队,即保证队列单调递减,从而队首元素就是队列的最大值
PS:使用 O(1)时间复杂度来获得队列或栈的最大值或者最小值,往往需要使用一个辅助的数据结构实现
java代码如下:
class MaxQueue{
	Deque<Integer> res,max;
	public MaxQueue(){
		res = new LinkedList<Integer>();
		max = new LinkedList<Integer>();
	}
	
	public int max_value(){
		if(max.isEmpty()) return -1;
		return max.peekFirst();
	}
	
	public void push_back(int value){
		res.addLast(value);
		while(!max.isEmpty() && max.peekLast() < value){
			max.removeLast();
		}
		max.addLast(value);
	}
	
	public int pop_front(){
		if(res.isEmpty()) return -1;
		int temp = res.peekFirst();
		if(temp == max.peekFirst()) max.removeFirst();
		res.removeFirst();
		return temp;
	}
}
                


















