map、set和哈希的区别:
#include
#include
using namespace std;
void test_set()
{
unordered_set s;
//set s;
s.insert(2);
s.insert(3);
s.insert(1);
s.insert(2);
s.insert(5);
//unordered_set::iterator it = s.begin();
auto it = s.begin();
while (it != s.end())
{
cout << *it << " ";
++it;
}
cout << endl;
for (auto e : s)
{
cout << e << " ";
}
cout << endl;
}
int main()
{
test_set();
return 0;
}
void test_map()
{
unordered_map dict;
dict.insert(make_pair("sort", "排序"));
dict.insert(make_pair("left", "左边"));
dict.insert(make_pair("left", "剩余"));
dict["string"]; // 插入 默认缺省值""
dict["left"] = "剩余"; // 修改
dict["string"] = "字符串"; // 修改
}
因为rand的随机数有数量限制,超过后会一直重复。
void test_op()
{
int n = 10000000;
vector v;
v.reserve(n);
srand(time(0));
for (int i = 0; i < n; ++i)
{
//v.push_back(i);
//v.push_back(rand()+i); // 重复少
v.push_back(rand()); // 重复多
}
size_t begin1 = clock();
set s;
for (auto e : v)
{
s.insert(e);
}
size_t end1 = clock();
size_t begin2 = clock();
unordered_set us;
for (auto e : v)
{
us.insert(e);
}
size_t end2 = clock();
cout << s.size() << endl;
cout << "set insert:" << end1 - begin1 << endl;
cout << "unordered_set insert:" << end2 - begin2 << endl;
size_t begin3 = clock();
for (auto e : v)
{
s.find(e);
}
size_t end3 = clock();
size_t begin4 = clock();
for (auto e : v)
{
us.find(e);
}
size_t end4 = clock();
cout << "set find:" << end3 - begin3 << endl;
cout << "unordered_set find:" << end4 - begin4 << endl;
size_t begin5 = clock();
for (auto e : v)
{
s.erase(e);
}
size_t end5 = clock();
size_t begin6 = clock();
for (auto e : v)
{
us.erase(e);
}
size_t end6 = clock();
cout << "set erase:" << end5 - begin5 << endl;
cout << "unordered_set erase:" << end6 - begin6 << endl;
}
961. 在长度 2N 的数组中找出重复 N 次的元素 - 力扣(LeetCode)
class Solution {
public:
int repeatedNTimes(vector& A) {
size_t N = A.size()/2;
// 用unordered_map统计每个元素出现的次数
unordered_map m;
for(auto e : A)
m[e]++;
// 找出出现次数为N的元素
for(auto& e : m)
{
if(e.second == N)
return e.first;
}
}
};
class Solution {
public:
vector intersection(vector& nums1, vector& nums2) {
// 用unordered_set对nums1中的元素去重
unordered_set s1;
for (auto e : nums1)
s1.insert(e);
// 用unordered_set对nums2中的元素去重
unordered_set s2;
for (auto e : nums2)
s2.insert(e);
// 遍历s1,如果s1中某个元素在s2中出现过,即为交集
vector vRet;
for (auto e : s1)
{
if (s2.find(e) != s2.end())
vRet.push_back(e);
}
return vRet;
}
};
ums2)
s2.insert(e);
// 遍历s1,如果s1中某个元素在s2中出现过,即为交集
vector vRet;
for (auto e : s1)
{
if (s2.find(e) != s2.end())
vRet.push_back(e);
}
return vRet;
}
};