How to get overlap range of two range

后端 未结 4 1541
眼角桃花
眼角桃花 2020-12-21 09:25

I have the following ranges in interval [1-15]

I want to find the overlap ranges between people 1 & 2.

Person1 [1, 3] [5, 10] Person2 [2, 4] [8, 15]

4条回答
  •  粉色の甜心
    2020-12-21 10:05

    Have a look at the merge step of the mergesort algorithm. If the ranges for each person are sorted this method can be adapted to compute the overlaps very easily.

    Loop
       Get the range that starts next (R1)
       if the next range of the other person (R2) starts before R1 ends
          Add the range from begin of R2 and min( end of R1 end of R2 ) to results
       Increase the counter for the person which gave you R1
    

    If your ranges are known to be non adjacent (i.e. if there is always at least one number between to consecutive ranges). The solution will also be. Else you might need an extra compaction step to ensure that adjacent ranges will be put into one range.

    The nice thing is that this works for any ordered type and not just ints, and you can intersect any number of ranges very fast ( O(n+m) ).

提交回复
热议问题