A range intersection algorithm better than O(n)?

前端 未结 9 709
悲&欢浪女
悲&欢浪女 2020-12-04 18:27

Range intersection is a simple, but non-trivial problem.

Its has been answered twice already:

  • Find number range intersection
  • Comparing date ra
9条回答
  •  有刺的猬
    2020-12-04 19:10

    Non Overlapping Ranges:

    Prep O(n log n):

    1. Make a array / vector of the ranges.
    2. Sort the vector by the end of the range (break ties by sorting by the start of the range)

    Search:

    1. Use binary search to find the first range with an End value of >= TestRange.Start
    2. Iterator starting at the binary search until you find an Start > TestRange.End:

      2a. If the range if the current range is within the TestRange, add it to your result.

提交回复
热议问题