How do I write a method that finds all the intersections in an array of ranges?

跟風遠走 提交于 2020-03-03 09:14:08

问题


I have array similar to this

[
 [0, 10]**,
 [1, 3]**,
 [5, 11]**,
 [14, 20]**,
 [10, 11]**
]

** Denotes an object containing the start and end indexes shown in the array

Now, the intersections are [1, 3], [5,10], [10,11]

What is the best way to write a method that returns the objects containing of the intersecting sets? (Could just store them in an array of conflicted stuff as we go along)

The biggest issue I'm having is how do I do this such that each object is compared with eachother object?

there are n! ways to do this (i think, I'm a bit rusty on my combinatorics)


回答1:


Sort the intervals by start time (or instead sort an array of indices by start time so you don't lose the indices).

After this you can do a single pass detecting all intersections/conflicts.

Range array[N];

sort(array);
int i=0;
while(i<N){
    Range curr = array[i];  //invariant: curr doesn't intersect with anyone befor it
    i++;
    while(i < N && array[i].start <= curr.end){
        output that curr and array[i] intersect;
        if(array[i].end > curr.end){
            curr = array[i]
        }
        i++;
    }
}


来源:https://stackoverflow.com/questions/7959579/how-do-i-write-a-method-that-finds-all-the-intersections-in-an-array-of-ranges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!