因为每个组合都有可能在指定范围内,最坏的情况是O([A][B]),基本上是O(n^2)
但是,如果您想要最好的简单算法,这就是我想出的。它开始类似于 user-targaryen 的算法,但以简单的方式处理重叠
Create three variables: x,y,Z and s (set all to 0)
Create a boolean 'success' and set to false
Calculate Z = B[y] - A[x]
if Z < L
increment y
if Z >= L and <= M
if success is false
set s = y
set success = true
increment y
store x,y
if Z > M
set y = s //this may seem inefficient with my current example
//but you'll see the necessity if you have a sorted list with duplicate values)
//you can just change the A from my example to {1,1,2,2,3} to see what I mean
set success = false
一个例子:
A = {1,2,3,4,5}
B = {3,4,5,6,7}
L = 2,M = 3
在本例中,第一对是 x,y。第二个数字是 s。第三对是值 A[x] 和 B[y]。第四个数字是 Z,即 A[x] 和 B[y] 之间的差值。最终值为 X 表示不匹配,O 表示匹配
0,0 - 0 - 1,3 = 2 O
increment y
0,1 - 0 - 1,4 = 3 O
increment y
0,2 - 0 - 1,5 = 4 X
//this is the tricky part. Look closely at the changes this makes
set y to s
increment x
1,0 - 0 - 2,3 = 1 X
increment y
1,1 - 0 - 2,4 = 2 O
set s = y, set success = true
increment y
1,2 - 1 - 2,5 = 3 O
increment y
1,3 - 1 - 2,6 = 4 X
set y to s
increment x
2,1 - 1 - 3,4 = 1 X
increment y
2,2 - 1 - 3,5 = 2 O
set s = y, set success = true
increment y
2,3 - 2 - 3,6 = 3 O
... and so on