What is Sliding Window Algorithm? Examples?

2019-01-03 13:28发布

While solving a geometry problem, I came across an approach called Sliding Window Algorithm.

Couldn't really find any study material/details on it.

What is the algorithm about?

2条回答
该账号已被封号
2楼-- · 2019-01-03 13:39

Generally speaking a sliding window is a sub-list that runs over an underlying collection. I.e., if you have an array like

[a b c d e f g h]

a sliding window of size 3 would run over it like

[a b c]
  [b c d]
    [c d e]
      [d e f]
        [e f g]
          [f g h]

This is useful if you for instance want to compute a running average, or if you want to create a set of all adjacent pairs etc.

查看更多
Luminary・发光体
3楼-- · 2019-01-03 13:45

This is the code of the sliding window protocol for an array of size n, where sum of k numbers is stored together in another array sum.The following code is in 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]);
        }
    }
}
查看更多
登录 后发表回答