【问题标题】:Data Structure for storing ranges of values that allows efficient comparision operation用于存储允许有效比较操作的值范围的数据结构
【发布时间】:2012-10-22 18:55:06
【问题描述】:

我正在寻找一种允许存储非重叠整数范围的数据结构 并比较数据结构中是否存在[被覆盖]的某个范围。

例如,在我存储 (0,9),(10,19),(30,29) 之后, 稍后我想检查范围 (1,11) 是否被覆盖,在这种情况下 算法给出“是”,而对于范围 (15,25),该算法给出“否”,因为未覆盖给定范围。

非常感谢。

【问题讨论】:

    标签: performance algorithm data-structures


    【解决方案1】:

    由于您正在处理整数的非重叠范围,我认为一个简单的 BST 可以完成这项工作(像 AVL 或 RB-tree 一样平衡,以防您想要严格的 O(logN) 性能)

    对于区间 [a-b] 构建以“a​​”为键的树。 节点结构类似于:

    struct node{
    int left;
    int right;
    struct node*left;
    struct node*right;
    };
    

    为了搜索:

    bool SearchOverlap(node* root, interval I){
    if(!root)
        return false;
    if(I.right < root->left)
        SearchOverlap(root->left, I);
    else if(I.left > root->right)
        SearchOverlap(root->right, I);
    else if(I.left > root->left && I.right < root->right)
        return true;
    else if(I.left < root->left && I.right < root->right)
        return SearchOverlap(root->left, new Interval(I.left, root->left));
    else if(I.left > root->left && I.right > root->right)
        return SearchOverlap(root->right, new Interval(root->right, I.right));
    }
    

    【讨论】:

    • 非常感谢您的示例代码。 STL 不提供区间树的实现吗?
    • 无 STL。不是我知道的。但我认为 Boost 库提供了一个 IntervalMap。
    • 很棒的想法,一个小错误:第二个 else if 应该是“I.left > root->left && I.right right”。如果我错了,请纠正我。
    • @takwing:您可以使用 std::map (仅针对此问题,不适用于一般区间树)。区间的左端是键,右端 - 值。
    【解决方案2】:

    您可能正在寻找 Interval Tree 数据结构,它旨在快速存储和搜索区间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      相关资源
      最近更新 更多