【问题标题】:set vs unordered set! Which is better to use?集合 vs 无序集合!哪个更好用?
【发布时间】:2020-06-16 08:22:08
【问题描述】:

我必须在 n 个元素的列表中找到唯一元素的数量。 我已经使用了 set 并且它被接受了,但是当我在其中一种情况下使用 unordered_set 时超出了时间限制。这怎么可能?

使用集合的代码

#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
set<int> s;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
s.insert(x);
}
cout << s.size() << "\n";
return 0;
}

使用 Unordered_set 的代码

#include <bits/stdc++.h>
 using namespace std;
 int main()
 {
 ios_base::sync_with_stdio(false);
 cin.tie(NULL);
 unordered_set<int> s;
 int n;
 cin >> n;
 for (int i = 0; i < n; i++)
 {
 int x;
 cin >> x;
 s.insert(x);
 }
 cout << s.size() << "\n";
 return 0;
 }

【问题讨论】:

    标签: c++ data-structures c++14


    【解决方案1】:

    set 在内部使用红黑树,因此它在内部像BST 一样执行操作,它会生成balanced tree,所以无论如何搜索肯定是logarithmic time,但插入到@987654325 @ 取决于正在使用的数据和实际确定哈希集中冲突次数的“内部哈希函数”,因此可能由于特定输入导致的冲突次数增加,它可能无法处理大量的碰撞,因为碰撞处理也需要时间,因为它可能采用两种标准方法中的任何一种

    【讨论】:

      【解决方案2】:

      测试用例包含的值散列非常严重,有很多冲突。
      unordered_set 中插入的最坏情况复杂度与集合大小呈线性关系。
      在最坏的情况下,set 中的插入是对数的。

      【讨论】:

        【解决方案3】:

        unordered_set insert() 操作的最坏情况时间复杂度为 O(n),而在 ordered_set 的情况下,时间复杂度为 O(log(n)),因为它在每次操作后保持自平衡 BST。 我建议您通过 CPP-reference 阅读以下文档,您可以找到与 c++ 相关的所有信息。

        参考资料: 对于 unordered_set:insert()

        (1)https://en.cppreference.com/w/cpp/container/unordered_set/insert

        对于ordered_set:insert()

        (2)https://en.cppreference.com/w/cpp/container/set/insert

        希望这会有所帮助.. 快乐编码..

        【讨论】:

          猜你喜欢
          • 2013-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-10
          • 1970-01-01
          • 2013-01-23
          • 2021-03-15
          • 1970-01-01
          相关资源
          最近更新 更多