Having a hash map to keep track of elements in another data structure

时间:2017-06-04 23:49:53

标签: algorithm

So sometimes I have a certain ds with certain functionalities which have a get time complexity of O(N) like a queue, stack, heap, etc.. I use one of these ds in a program which just needs to check whether a certain element is in one of theses ds, but because they have a get complexity of O(N), it is the pitfall in my algorithm.

If memory isn't much of my worries, would it be poor design to have a hashmap which keeps track of the elements in the restricted data structure? Doing this would essentially remove the O(N) restriction and allow it to be O(1).

1 个答案:

答案 0 :(得分:0)

在许多情况下都有保证补充哈希表。但是,维持“并行哈希”可能会成为一种负担。

当您需要快速检查成员资格时,您描述的情况通常使用基于散列的集合(HashSet<T>std::unordered_set<T>等建模,具体取决于语言)。这些结构的缺点是没有指定元素的顺序,并且它们不能有重复。

根据库的不同,您可以访问修复这些缺点的数据结构。例如,Java提供了LinkedHashSet<T>,它提供了可预测的枚举顺序,而C ++提供了std::unordered_multiset<T>,它允许重复。