A range intersection algorithm better than O(n)?

前端 未结 9 742
悲&欢浪女
悲&欢浪女 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:05

    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)
    3. Make a second vector of ints. This represents the point at which you can stop searching.

      int stop[size];
      stop[size-1] = Ranges[size - 1].start;
      for (int i = size - 2; i >= 0; i--)
      {
          stop[i] = min(Ranges[i].start, stop[i+1]);
      }
      

    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 stop[i] > TestRange.End:

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

提交回复
热议问题