[英]More memory efficient algorithm for finding overlap in ranges
In this question, the answer included an algorithm to find overlap of a list of ranges on a given range. 在此问题中,答案包括一种算法,用于查找给定范围上的范围列表的重叠。 But in my situation I have a list of
n
integers, which when grouped into n^2
pairs form ranges. 但是在我的情况下,我有一个由
n
整数组成的列表,将它们分组为n^2
对时会形成范围。 For example if we take array[i]
and array[j]
from the integer array, (array[i]-array[j],array[i]+array[j])
make a range. 例如,如果我们从整数数组中获取
array[i]
和array[j]
,则(array[i]-array[j],array[i]+array[j])
构成一个范围。 But in order to implement the suggested algorithm, the solution is of O(n^2)
memory complexity. 但是为了实现建议的算法,解决方案是
O(n^2)
存储复杂度。 Can it be optimized (in terms of memory) further? 是否可以进一步优化(在内存方面)?
Example: I have a larger range (l,r)
, and I have to find how many integers in (l,r)
lie in at least any one of the list of ranges.For example, the given integer array is {1,2,3}
. 例子:我有一个更大的范围
(l,r)
,我必须找出(l,r)
中至少有一个范围列表中有多少个整数,例如,给定的整数数组是{1,2,3}
。 So all possible ranges are (2-1,1+2), (3-1,1+3), (3-2,3+2)
. 因此所有可能的范围是
(2-1,1+2), (3-1,1+3), (3-2,3+2)
。 Suppose (l,r)
is (2,7)
. 假设
(l,r)
是(2,7)
。 Then since (2,5)
exist in at least one of them 4
is the answer. 然后,由于
(2,5)
至少存在于其中4
中,因此答案为。
Start by sorting the array (if it isn't already sorted). 首先对数组进行排序(如果尚未排序)。 Then note that the only ranges worth considering are those where
j == i-1
. 然后注意,唯一值得考虑的范围是
j == i-1
。
To understand why consider the following array: 要了解为什么考虑以下数组:
{2,3,5,8}
Then the possible ranges are: 那么可能的范围是:
i=3 j=2 ==> (8-5,8+5) = (3,13)
i=3 j=1 ==> (8-3,8+3) = (5,11)
i=3 j=0 ==> (8-2,8+2) = (6,10)
i=2 j=1 ==> (5-3,5+3) = (2,8)
i=2 j=0 ==> (5-2,5+2) = (3,7)
i=1 j=0 ==> (3-2,3+2) = (1,5)
Notice that the ranges for j < i-1
are always strict subsets of the range where j == i-1
, so those ranges don't need to be considered. 请注意,
j < i-1
的范围始终是j == i-1
的范围的严格子集,因此不需要考虑这些范围。 So you only need to consider O(n) ranges. 因此,您只需要考虑O(n)范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.