A range intersection algorithm better than O(n)?

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

    Just as a quad tree works for a set of 2d points, a simple binary tree should work for this case. Build a tree with your ranges.

    To explain further: Each node in the tree contains two integers, the beginning and end of the range, and the two children if it's not a leaf node. To find the ranges that your input range spans, then starting at the top of the tree

      - if the node range intersects the input range:
         - if it's a leaf node, then add the range to your result list
         - if it's not a leaf node, then traverse down to the child nodes and repeat this process.
    

    It should be O(logN)

    Further detail: The binary tree would be structured like a 1-d version of a quad tree. Each node would have three integers (sorry I said two above, but now I realize you need three), the lowest representing the lowest value of the lowest range that's below this node, the highest representing the highest value of the highest range that's below this node, and the pivot. The left child would span from this node's lowest to its pivot. The right child would span from this node's pivot to this node's highest. If there is only one range that goes from "lowest" to "highest", you wouldn't have a pivot and this would be a leaf. Ideally you'd pick the pivots for each node to keep the tree balanced.

提交回复
热议问题