且构网

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

给定一组区间,如何找到它们之间的最大交点数,

更新时间:2022-06-25 10:41:16

标准的解决方案是将区间处理成一组(开始,结束)点.例如 (1,3) 生成 {1, begin}, {3, end}.然后对点进行排序并从左到右扫描,将 begin 计为 +1,将 end 计为 -1.计数器达到的最大值为最大重叠间隔数.

The standard solution is to process the intervals into a set of (begin,end) points. For example (1,3) generates {1, begin}, {3, end}. Then sort the points and scan left to right, counting begin as +1, end as -1. The max value reached by the counter is the maximum number of overlapping intervals.

这是从问题中的示例生成的中间数组:

This is the intermediate array generated from the example in the question:

[(1, 'begin'),
 (3, 'begin'),
 (5, 'end'),
 (6, 'begin'),
 (7, 'begin'),  # <--- counter reaches 3, its maximum value here.
 (8, 'end'),
 (9, 'end'), (10, 'end')]

这里有一个小问题.(1,end)(1,begin) 之前还是之后?如果您将间隔视为开放,那么它应该在前面 - 这样 (0,1) &(1,2) 不会算作相交.否则它应该在后面,这些间隔将被视为相交间隔.

There is a minor tricky point here. Does (1,end) go before or after (1,begin)? If you treat intervals as open, then it should go before - this way (0,1) & (1,2) won't be counted as intersecting. Otherwise it should go after and these intervals will count as intersecting ones.