两个排序数组中的最大对数
这不是一个原始问题。我遇到了一个复杂的问题,现在简化为以下问题:
有两个排序数组,A
和B
,其中m
和n分别为
元素,m = \Theta(n)
在 o(mn)
时间内运行的算法能否找到满足 A[i]-B[j] <= T
的最大对数,其中 T 是某个持续的?这怎么能做到呢?
编辑:
这些对应该是不相交的,即一个元素最多只能被选择一次。
算法应该在little-o(mn)内运行,这意味着在mn时间内运行的解决方案是不可接受的。
是否也可以找到我们选择的对?
说明:
如果数组是 a_1, a_2, ..., a_m
和 b_1, b_2, ..., b_n
,我需要找到对 (a_i, b_j)
使得 |a_i - b_j| <= T
。不允许多次选择一个元素。我们怎样才能最大化给定数组的对的数量?
This is not an original problem. I had a complex problem which is now reduced to the following:
There are two sorted arrays, A
and B
with m
and n
elements respectively, m = \Theta(n)
Can an algorithm that runs in o(mn)
time find the maximum number of pairs such that A[i]-B[j] <= T
where T is some constant? How can this be done?
edit:
The pairs should be disjoint, i.e. one element can be selected at most once.
The algorithm should run in little-o(mn) meaning that a solution that runs in mn time is not acceptable.
Is it also possible to find the pairs that we select?
Clarification:
If the arrays are a_1, a_2, ..., a_m
and b_1, b_2, ..., b_n
, I need to find pairs (a_i, b_j)
such that |a_i - b_j| <= T
. It is not allowed to choose an element more than once. How can we maximize the number of pairs given the arrays?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新2:
更新后的问题(仅使用任一数组中的元素一次,获取对,并且值的绝对差必须低于
T
)可能能够在O(n+m)时间内完成。我还没有充分考虑下面的算法来决定它是否总是获得最大数量的对,但在大多数情况下应该:UPDATE 2:
The updated question (only use an element from either array once, get the pairs, and the absolute difference of the values must be below
T
) might be able to be done in O(n+m) time. I haven't thought through the algorithm below enough to decide if it will always get the maximum number of pairs or not, but it should in most cases:在
O(n lg n) = O(m lg m)
中:根据A
的元素创建平衡二叉搜索树,并在每个节点中存储a的索引元素和元素值。对于B
的每个元素,搜索小于或等于B[j] + T
的最大值。这个数字的索引会告诉你有多少个数字小于或等于这个数字。In
O(n lg n) = O(m lg m)
: Create a balanced binary search tree from the elements ofA
, and store in each node the index of an element together with the element value. For each element ofB
, search for the greatest value that is less than or equal toB[j] + T
. The index of this number will tell you how many numbers are smaller than or equal to this number.如果您想要匹配
|A[i]-B[j]|的对的数量<= T
,其中每个A[i]
和B[j]
在所有对中仅使用一次:此算法扫描
中的最小范围>B
,并确保B
中没有元素被使用两次。If you want the number of pairs matching
|A[i]-B[j]| <= T
, where eachA[i]
andB[j]
are used only once in all pairs:This algorithm scans minimal ranges in
B
, and makes sure that no element inB
is used twice.