本文最后更新于 6 天前。
与一般的单调队列问题不同(如力扣239),力扣239中队列的大小是固定的一直都是3,但在这道笔试题中,队列是类似逐渐进入再逐渐出去的样子,队列大小从3,增大到4,再持续为4,再减小到3,(具体和k有关)在笔试时,我也花了很长时间想,后来想到一个解决办法,根据k的值,向数组前面和后面加入若干极大值,这样问题就转换成了固定队列大小,直接按固定队列大小输出即可。
实例程序:
public class a {
public static void main(String[] args) {
List<Integer> queue = new LinkedList<>();
List<Integer> x = new ArrayList<>(Arrays.asList(999, 3, 6, 7, 8, 9, 2, 1, 10, 999));
int k = 2;
k+=2;
for(int i = 0; i < 10; i++){
if(!queue.isEmpty() && i - k + 1 > queue.get(0)){
queue.remove(0);
}
while(!queue.isEmpty() && x.get(queue.get(queue.size() - 1)) >= x.get(i)){
queue.remove(queue.size() - 1);
}
queue.add(i);
if(i >= k - 1){
System.out.println(queue.get(0) - 1);
}
}
}
}