搜索的间隔的列表间隔重叠?间隔、列表

2023-09-10 23:01:36 作者:纵横四海

说出[A,B]重presents上实线的时间间隔从A到B,读取< B,含(即,[A,B] =设定的所有x的,使得与所述; = X&其中; = b)中。另外,说[A,B]和[C,D]是重叠,如果它们共享任意x,使得x是在两个[A,B]和[C,D]。

Say [a,b] represents the interval on the real line from a to b, a < b, inclusive (ie, [a,b] = set of all x such that a<=x<=b). Also, say [a,b] and [c,d] are 'overlapping' if they share any x such that x is in both [a,b] and [c,d].

由于间隔的列表,([X1,Y1],[X2,Y2],...),什么是最有效的方式找到所有的时间间隔与[X,Y]重叠?

Given a list of intervals, ([x1,y1],[x2,y2],...), what is the most efficient way to find all such intervals that overlap with [x,y]?

显然,我可以尝试每一个得到它的O(N)。但我在想,如果我能间隔列表进行排序以某种巧妙的方式,我能找到/一个/经二分查找重复项为O(log N),然后从列表中的位置东张西望找到所有重叠的区间。但是,我怎么排序的时间间隔,使得这种战略将工作?

Obviously, I can try each and get it in O(n). But I was wondering if I could sort the list of intervals in some clever way, I could find /one/ overlapping item in O(log N) via a binary search, and then 'look around' from that position in the list to find all overlapping intervals. However, how do I sort intervals such that such a strategy would work?

请注意,有可能是元件之间的重叠列表中的项目本身,这是什么使这个硬

Note that there may be overlaps between elements in the list items itself, which is what makes this hard.

我已经试过了通过排序间隔由他们左端,右端,中间,但没有似乎导致穷举搜索。

I've tried it by sorting intervals by their left end, right end, middle, but none seem to lead to an exhaustive search.

帮助?

推荐答案

[A,B]重叠与[X,Y]当且仅当B> X和A&LT;年。排序间隔由他们的第一个元素给你的时间间隔匹配日志时的首要条件。排序间隔由他们最后的元素给你的时间间隔匹配日志的时间第二个条件。承担由此产生集的交叉点。

[a, b] overlaps with [x, y] iff b > x and a < y. Sorting intervals by their first elements gives you intervals matching the first condition in log time. Sorting intervals by their last elements gives you intervals matching the second condition in log time. Take the intersections of the resulting sets.