问题
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?
回答1:
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.
回答2:
Sliding window is a problem solving technique for problems involves arrays/lists. These problems are easy to solve using a brute force approach in O(n^2) or O(n^3). Using the 'sliding window' technique, we can reduce the time complexity to O(n).
Great article on this is here: https://medium.com/outco/how-to-solve-sliding-window-problems-28d67601a66
So the first thing you want to be able to do is to identify a problem that uses a sliding window paradigm. Luckily, there are some common giveaways:
The problem will involve a data structure that is ordered and iterable like an array or a string
You are looking for some subrange in that array/string, like a longest, shortest or target value.
There is an apparent naive or brute force solution that runs in O(N²), O(2^N) or some other large time complexity.
But the biggest giveaway is that the thing you are looking for is often some kind of optimal, like the longest sequence or shortest sequence of something that satisfies a given condition exactly.
回答3:
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]);
}
}
}
来源:https://stackoverflow.com/questions/8269916/what-is-sliding-window-algorithm-examples