11.队列的最大值(292)
- 题目描述:定义一个队列并实现函数max得到队列里的最大值。要求max,pushBack,popFront的时间复杂度都是o(1)。
- 思路:用一个双端队列来存放数据元素;再用一个双端队列来存放最大值(相当于一个滑动窗口)
package _11.队列的最大值;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
public class QueueWithMax {
private Deque<Integer> dequeData;
private Deque<Integer> dequeMax;
public QueueWithMax() {
super();
this.dequeData = new LinkedList<Integer>();
this.dequeMax = new LinkedList<Integer>();
}
public void push_back(int number) {
dequeData.addLast(number);
while(!dequeMax.isEmpty() && number > dequeMax.getLast()){
dequeMax.removeLast();
}
dequeMax.addLast(number);
}
public void pop_front() {
if(dequeData.isEmpty()){
return;
}
Integer first = dequeData.removeFirst();
if(dequeMax.getFirst() == first){
dequeMax.removeFirst();
}
}
public int max(){
if(dequeData.isEmpty()){
return 0;
}
return dequeMax.getFirst();
}
public static void main(String[] args) {
QueueWithMax test = new QueueWithMax();
test.push_back(2);
test.push_back(1);
test.push_back(3);
test.push_back(3);
test.pop_front();
test.pop_front();
System.out.println(test.max());
}
}