查找对:(Ai, Bi) where Ai - Bi < X0,
现在,
Ai - Bi < X0,
=> Ai - X0 < Bi
这意味着B 中任何大于(Ai - X0) 的元素都会导致Ai - Bi < X0
所以基本上,您必须在B 中搜索大于其他值的元素,例如P。
您可以在O(lgN) 时间轻松搜索排序数组中的元素。在这种情况下,您将需要修改后的二进制搜索来查找大于给定值的值的索引。
您可以通过以下方式实现这一目标:(Click Here)
这是完整的算法:
getPairs(A,B,X0)
sort(B)
pairs = []
for each element Ai in A do:
P = Ai - X0
index = modifiedBinarySearch(B, P)
while ( index < B.length ) do
pairs.push( { Ai, Bindex } )
index++
done
done
return pairs
done
时间复杂度:
Sorting array of N elements: O(NlgN)
Iterating over array of N elements: O(N)
The inner while loop: O(N)
Thus, overall complexity: O(NlgN)
如果您不确定内部 while 循环的耗时 O(N),请在 cmets 中告诉我。