常见问题--窗口问题
题目情景:给定一些数据 给定窗口大小 找到窗口中的大数和小数 输出
一般数据量很大百万*百万
优化 : 考虑用队列存储 因为窗口华东过程中 窗口头元素会弹出 下一个元素会
进入,刚好队列符合条件
为何用单调队列呢?因为下一个进入的元素一定会和此时里面所有的元素比较
单调队列解决了这个问题,优化了时间
用hh表示对头 tt表示队尾
q[] 数组 表示队列 存储的是元素的下标
a[] 数组 表示数据
import java.util.*;
import java.io.*;
public class Main {
static final int N = 1000010;
static int[] a, q;
static {
a = new int[N];
q = new int[N];
}
public static void main(String[] args) throws IOException {
Scanner sin = new Scanner(new BufferedInputStream(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = sin.nextInt(), k = sin.nextInt();
for(int i=0; i<n; i++){
a[i] = sin.nextInt();
}
int hh = 0;
int tt = 0;
for(int i=0; i<n; i++){
while(q.length > 0 && q[tt] > a[i]) tt --;
q[++tt] = a[i];
if(i - k >= 1 && q[hh] == a[i-k]) hh ++;
if(i >= k) System.out.print(q[hh] + " ");
}
bw.write("\n");
hh = 0;
tt = -1;
for(int i=0; i<n; i++){
if(hh <= tt && i - k + 1 > q[hh]) hh++;
while(hh <= tt && a[q[tt]] <= a[i]) tt--;
q[++tt] = i;
if(i >= k - 1) bw.write(a[q[hh]] + " ");
}
bw.flush();
sin.close();
bw.close();
}
}