在解决几何问题时,我遇到了一种称为滑动窗口算法的方法。
无法真正找到任何研究材料/细节。
算法是什么?
一般而言,滑动窗口是在底层集合上运行的子列表。即,如果你有一个类似的数组
[a b c d e f g h]
一个大小为3的滑动窗口就像是一样
[a b c]
[b c d]
[c d e]
[d e f]
[e f g]
[f g h]
如果您想要计算运行平均值,或者如果要创建一组所有相邻对等,这将非常有用。
这是大小为n的数组的滑动窗口协议的代码,其中k个数字的总和一起存储在另一个数组和中。以下代码用Java表示。
import java.io.*;
class deva
{
public static void main(String args[])throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
int[] a = new int[n];
for(int i=0; i<n; i++)
a[i] = Integer.parseInt(in.readLine());
int k = Integer.parseInt(in.readLine());
int[] sum = new int[n-k+1];
for(int i=0; i<k; i++)
sum[0] += a[i];
System.out.println(sum[0]);
for(int i=1; i<n-k+1; i++)
{
sum[i] = sum[i-1] + a[i+k-1] - a[i-1];
System.out.println(sum[i]);
}
}
}