标签:目的 inpu iter 窗口 滑动窗口 while puts 输出流 log
题目链接:
https://www.acwing.com/problem/content/156/
题解:
做滑动窗口,一般先假想成普通队列来做,再分析题目的单调性,改进优化
AC代码:
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
// 对输入数据进行初始化
String[] s1 = reader.readLine().split(" ");
int n = Integer.parseInt(s1[0]);
int k = Integer.parseInt(s1[1]);
int[] a = new int[n], q = new int[n];
String[] s = reader.readLine().split(" ");
for (int i = 0; i < n; i++)
a[i] = Integer.parseInt(s[i]);
int hh = 0, ee = -1;
for(int i = 0;i < n;i ++) {
while(hh <= ee && q[hh] < i - k + 1) hh++;
while(hh <= ee && a[q[ee]] >= a[i] ) ee--;
q[++ee] = i;
if(i >= k - 1) log.write(a[q[hh]] + " ");
}
log.write("\n");
hh = 0; ee = -1;
for(int i = 0;i < n;i ++) {
while(hh <= ee && q[hh] < i - k + 1) hh++;
while(hh <= ee && a[q[ee]] <= a[i] ) ee--;
q[++ee] = i;
if(i >= k - 1) log.write(a[q[hh]] + " ");
}
// 关闭输入输出流
log.flush(); // 如果不flush,没有标准输出
reader.close();
log.close();
}
}
标签:目的 inpu iter 窗口 滑动窗口 while puts 输出流 log
原文地址:https://www.cnblogs.com/doubest/p/13024118.html