Data structure for quick time interval look up

后端 未结 4 1526
一整个雨季
一整个雨季 2020-12-02 17:31

I have a set of time intervals In = (an, bn). I need to run lots of look ups where I\'m given a time t and need to quickly return the intervals that conta

相关标签:
4条回答
  • 2020-12-02 18:10

    What you are looking for is an Interval Tree (which is a type of Range Tree).

    These have logarithmic lookup time like other tree structures (e.g., RB trees), so you should see comparable performance to using something like a Java TreeMap or an STL map.

    • Code for Red-black trees and interval trees from MIT
    • There is a C++ implementation in the CGAL Library.
    • Here's a C# Implementation
    0 讨论(0)
  • 2020-12-02 18:20

    You are welcome to check out the C# implementation I've posted on CodePlex for IntervalTree which solve this problem exactly.

    Ido.

    0 讨论(0)
  • 2020-12-02 18:25

    This is basically a space partitioning question. You have a large space with containers and a specific point in that space, what containers does it touch? A lot of games have to solve this problem, so it wouldn't be a bad idea to start there. Look for articles on "broad phase collision detection".

    The simplest way to do this is to divide your number space into a constant number of pieces. Each piece knows which sets intersect with it, something that you calculate whenever a new set is added. Now, rather than testing every single set when you have a point, you only need to check the sets contained within the piece that the point is in.

    Another general and efficient algorithm used is Binary Space Partioning. This algorithm subdivides your space into two sides. Each side would know which sets intersect with it. You can recursively repeat this process to your desired precision (although it doesn't make sense to ever create a subdivision smaller than the range of your smallest set).

    0 讨论(0)
  • 2020-12-02 18:29

    Your problem is only one dimensional, so it's a bit simpler than the space partitioning problems found in most games. You could have just a simple BST and in each leaf remember list of intervals to the left fromt the leaf.

    if you had intervals A (0, 10) and B (5, 15), then the leaves of the tree would be (0 with empty list), (5 with A), (10 with A, B) and (15 with B).

    0 讨论(0)
提交回复
热议问题