Counting Overlaps of Integer Ranges

后端 未结 3 1498
暗喜
暗喜 2021-02-10 03:28

I\'ve been stumped on this algorithm for quite a bit.

Say there are four ranges of integers. Each range has a Start and an End value.

Range A: 0,5
Range         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-10 04:02

    You can solve this in O(N ln N) time (for sorting) followed by the same amount of time for outputting results. If the number range is large, O(N ln N) is better than the O(M·N) time of the method suggested in a comment (where M = total range of numbers covered by the ranges).

    Sort the N ranges into ascending order, keyed by Start value, say in array S. Initialize an empty priority queue P. Initialize a depth-count D to zero, and the current “reach” to R = S[0].Start.

    While S[i].Start=R, push S[i].End on P and advance i and D. When S[i].Start>R, yield the tuple (R, p.top, D). Pop P to R and then decrease D by one and pop P while P.top==R.

    Repeat the above paragraph while i.

提交回复
热议问题