A range intersection algorithm better than O(n)?

前端 未结 9 760
悲&欢浪女
悲&欢浪女 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 18:52

    Edit: It sounds like this solution is more or less an Interval Tree. A more complete implementation of an Interval Tree can be found here.

    class TreeNode
    {
    public:
        long pivot;
        List leaves;  //Any ranges that intersect the pivot
        TreeNode left;        //Tree nodes that fall to the left of the pivot
        TreeNode right;       //Tree nodes that fall to the right of the pivot
    };
    

    Prep O(n log n):

    1. Create the list of ranges
    2. Pick the pivot points (possibly by using a sorted list of the end dates.) ??
    3. Build your tree.

    Search:

    1. Use binary search to find the first pivot that is >= TestRange.End
    2. Traverse the tree until the pivot > TestRange.Start

      2a. Add the leaves to your result.


    Example:

    Ranges:

    • 0 - 2
    • 1 - 2
    • 2 - 3
    • 1 - 4
    • 2 - 4
    • 0 - 5
    • 4 - 5
    • 2 - 6
    • 3 - 7

    Tree:

                                 4
                   --------------+------------------
                   3             |                 7
                   |            1-4                |
                   |            2-4                |
                   |            0-5                |
                   |            4-5                |
          ---------+------                 --------+--------
          2        |    null              6        |       null
     -----+----   2-3                 ----+----   3-7
    null  |  null                   null  |  null    
         0-2                             2-6
         1-2
    

提交回复
热议问题