且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可能的面试问题:如何查找所有重叠区间

更新时间:2022-01-13 09:42:22

扔区间的端点到一个数组,将它们标记为无论是开始 - 或终点。您可以按照通过将终点前的启动点突破的关系,如果间隔关闭,或者反过来,如果他们是半开的。

Throw the endpoints of the intervals into an array, marking them as either start- or end-points. Sort them by breaking ties by placing end-points before start-points if the intervals are closed, or the other way around if they're half-open.

1S, 2S, 3E, 4E, 5S, 10E, 12S, 13S, 14E, 15E

然后通过列表循环,跟踪有多少时间间隔是在(这相当于加工的终点减去起点数号)。每当我们到了一个起始点,而我们已经在一个区间,这意味着我们必须有重叠的区间。

Then iterate through the list, keeping track of how many intervals we're in (this equates to number of start-points processed minus number of end-points). Whenever we hit a start-point while we have are already in an interval, this means we must have overlapping intervals.

1S, 2S, 3E, 4E, 5S, 10E, 12S, 13S, 14E, 15E
    ^                          ^
   overlap                    overlap

我们可以找到它的时间间隔与通过存储数据以及结束点,并跟踪这些重叠的区间我们在

We can find which intervals overlap with which by storing data alongside the end-points, and keeping track of which intervals we're in.

这是一个O(N logN)的解决方案,整理是主要因素。

This is an O(N logN) solution, with sorting being the main factor.