问题
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