gpt4 book ai didi

c++ - 设置与无序设置!哪个更好用?

转载 作者:行者123 更新时间:2023-12-02 09:53:25 25 4
gpt4 key购买 nike

我必须在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;
}

最佳答案

set在内部使用一棵红黑树,因此它像BST一样在内部进行操作,并且生成balanced tree,因此在任何情况下都可以肯定地搜索logarithmic time,但是插入unordered_set取决于所使用的数据和“内部哈希函数” ”实际上决定了散列集中的冲突数,因此由于特定输入导致的冲突数较高,可能无法处理大量冲突,因为冲突处理还需要时间,因为可以采用2种标准方法中的任何一种

关于c++ - 设置与无序设置!哪个更好用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62404069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com