Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

arrays - Given a set of intervals, how to find the maximum number of intersections among them,

Let's say you are given a set of intervals (1,5), (6,10), (3,8), (7,9). The output I expect is 3 since there are maximum 3 intervals (3,8), (6,10) and (7,9) that intersect with each other. Note that, (1,5) and (3,8) also intersect with each other but that's only 2 of them. So the answer here is going to be 3, since 3 is the maximum number of intervals that intersect with each other.

What are some efficient ways of finding it? I guess the first step would be to sort the intervals according to the starting value. Any suggestions after that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')]

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...