Fast intersection of several interval ranges?

前端 未结 1 2000
南旧
南旧 2021-01-14 19:32

I have several variables, all of which are numeric ranges: (intervals in rows)

a = [ 1 4; 5 9; 11 15; 20 30];
b = [ 2 6; 12 14; 19 22];
c = [ 15 22; 24 29; 3         


        
相关标签:
1条回答
  • 2021-01-14 20:10

    O(N lg N) method:

    1. Convert each interval (t_A, t_B) to a pair of tagged endpoints ('begin', t_A), ('end', t_B)

    2. Sort all the endpoints by time, this is the most expensive step

    3. Do one pass through, tracking nesting depth (increment if tag is 'start', decrement if tag is 'end'). This takes linear time.

      • When the depth changes from 2 to 3, it's the start of an output interval.
      • When it changes from 3 to 2, it's the end of an interval.
    0 讨论(0)
提交回复
热议问题