输出列表地图

时间:2016-07-25 14:19:28

标签: algorithm data-structures

我有一个列表地图,每个列表都有整数。输出是在每个其他元素列表中不相交的元素集的映射。

对于前: 以下是列表地图

清单1 - 1,2,3,4,5

清单2 - 3,4,5,6,7,8

清单3 - 1,2,3,5,6,7,8

所有名单的交叉点为 - 3,5 输出应该是列表的映射(不包括3,5)

清单1 - 1,2,4

清单2 - 4,6,7,8

清单3 - 1,2,6,7,8

我有一个使用2 for循环的解决方案,但它具有O(n * n)复杂度。试图找到最佳解决方案。任何指针赞赏。

1 个答案:

答案 0 :(得分:1)

您可以使用哈希表来表示不同的集合。这样计算整个交叉点是 O(M),其中 M 是所有集合中元素的总数。

然后,您需要计算原始集和计算的交集之间的集合差异。同样,使用哈希表 O(K * N)可以非常快速地完成此操作,其中 K 是整个交叉点中元素的数量, N 套数。

算法的结构将使用两个非嵌套的for循环。第一个计算所有集合的交集,第二个计算所有集合中的冗余元素。

您将在Coliru上找到C ++中正在运行的示例。

#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_set>

// Complexity: O(min(set1.size(), set2.size()))
template <typename T>
std::unordered_set<T> intersection(std::unordered_set<T> const& set1, std::unordered_set<T> const& set2) {
    if (set2.size() < set1.size()) {
        return intersection(set2, set1);
    } else {
        std::unordered_set<T> inter;
        for (auto const& el1 : set1) {
            if (std::find(set2.cbegin(), set2.cend(), el1) != set2.cend()) {
                inter.emplace(el1);
            }
        }
        return inter;
    }
}

using int_hashset = std::unordered_set<int>;

int main()
{
    std::vector<int_hashset> input_sets = {{1, 2, 3, 4, 5},
                                           {3, 4, 5, 6, 7, 8},
                                           {3, 5, 6, 7, 8}};

    auto inter_set = *input_sets.cbegin();
    // Complexity: O(number of elements)
    for (auto it = input_sets.cbegin()+1; input_sets.cend() != it; ++it) {
        inter_set = intersection(inter_set, *it);
    }
    for (auto const& i : inter_set) {
        std::cout << "Elem in overall intersection: " << i << '\n';
    }

    // O(N*inter_set.size())
    for (auto& input_set : input_sets) {
        // O(inter_set.size())
        for (auto el : inter_set) {
            input_set.erase(el);
        }
    }

    int i = 0;
    for (auto const& input_set : input_sets) {
        ++i;
        for (auto el : input_set) {
            std::cout << "Element in set " << i << ": " << el << '\n';
        }
    }
    return 0;
}

注意:这是摊销的复杂性。如果您的集合中存在大量冲突,复杂性将会提高。