Counting Overlaps of Integer Ranges

后端 未结 3 1258
别那么骄傲
别那么骄傲 2021-02-10 03:21

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 03:51

    A range x intersects the input range y if:

    x.End >= y.Start AND y.End >= x.Start
    

    So, for a given input, just loop through your collection of ranges and see which satisfy the above condition.

    If your given collection of ranges doesn't change very often, and your collection of ranges gets much larger than the 4 you stated in the problem description, then sort them first so that you can more efficiently search for the ranges that intersect your input, rather than looping through all of them.

    If the given collection of ranges changes often, the sorting could be too expensive, and it would then be smarter to just loop through all of them each time.

提交回复
热议问题