哈希集合与哈希表的刷题总结
概念
使用哈希函数将键映射到存储桶
支持快速插入和搜索
1、设置哈希函数:y = x % 5
2、插入:我们通过哈希函数解析键,将它们映射到相应的桶中。
例如,1987 分配给桶 2,而 24 分配给桶 4。
3、搜索:我们通过相同的哈希函数解析键,并仅在特定存储桶中搜索。
如果我们搜索 1987,我们将使用相同的哈希函数将1987 映射到 2。因此我们在桶 2 中搜索,我们在那个桶中成功找到了 1987。
如果我们搜索 23,将映射 23 到 3,并在桶 3 中搜索。我们发现 23 不在桶 3 中,这意味着 23 不在哈希表中。
哈希集合:#include < unordered_set >
#include <iostream>
#include <unordered_set>
using namespace std;
int main(){
unordered_set<int> hashset;
hashset.insert(3);
hashset.insert(3);
hashset.insert(3);
hashset.insert(3);
hashset.insert(2);
hashset.insert(1);
hashset.erase(2);
int isHave = hashset.count(3);
int Nums = hashset.size();
//for(int i=0; i<hashset.size(); i++){
// cout << hashset[i] << '\t';
//}
for(auto it=hashset.begin(); it!=hashset.end(); ++it){
cout << (*it) << '\t';
}
cout << endl;
hashset.clear();
cout << hashset.empty() << endl;
return 0;
}
}
哈希映射:#include < unordered_map >
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
unordered_map<int, int> hashmap;
hashmap.insert(make_pair(0,-1));
hashmap.insert(make_pair(100,3));
//cout << hashmap[0] << endl;
//cout << hashmap[1] << endl;
//cout << hashmap[2] << endl;
for (auto it = hashmap.begin(); it != hashmap.end(); ++it) {
cout << "(" << it->first << "," << it->second << ") ";
}
cout << endl;
hashmap.erase(0);
hashmap[2] = 109;
cout << hashmap.count(0) << endl;
cout << hashmap.count(1) << endl;
cout << hashmap.count(2) << endl;
cout << hashmap.count(3) << endl;
cout << hashmap.count(4) << endl;
cout << hashmap.count(5) << endl;
cout << hashmap.size() << endl;
for (auto it = hashmap.begin(); it != hashmap.end(); ++it) {
cout << "(" << it->first << "," << it->second << ") ";
}
cout << endl;
cout << hashmap.empty() << endl;
hashmap.clear();
cout << hashmap.empty() << endl;
return 0;
}
哈希集合查重模板
bool findDuplicates(vector<Type>& keys) {
// Replace Type with actual type of your key
unordered_set<Type> hashset;
for (Type key : keys) {
if (hashset.count(key) > 0) {
return true;
}
hashset.insert(key);
}
return false;
}
哈希映射表查重模板
/*
* Template for using hash map to find duplicates.
* Replace ReturnType with the actual type of your return value.
*/
ReturnType aggregateByKey_hashmap(vector<Type>& keys) {
// Replace Type and InfoType with actual type of your key and value
unordered_map<Type, InfoType> hashtable;
for (Type key : keys) {
if (hashmap.count(key) > 0) {
if (hashmap[key] satisfies the requirement) {
return needed_information;
}
}
// Value can be any information you needed (e.g. index)
hashmap[key] = value;
}
return needed_information;
}
哈希集合取交集[349]
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
if(nums1.empty() || nums2.empty()) return {
};
unordered_set<int> h1;
unordered_set<int> h2;
vector<int> h3;
for(int key : nums1