题目:
前几天刚学完了STL,今天就来了一道Hash集合题,可以说是很好了,能帮我复习一下知识点。
主要事项如下:
1.哈希表长度的选取要保证为质数。因为这样才能保证哈希表上的每一个位置都被有效运用。
STL里面的哈希表是可以动态增长并且对全部元素做Rehash的,这里我就先不实现了,拿题解里面的质数769来做总长。
2.使用的是链表解决冲突。 STL底层也是使用链表来解决冲突的。
3.hash函数是比较简单的求模
4.其余的没什么好说的,根据哈希表的特性,正常写就行了。
#include<iostream>
#include<vector>
#include<list>
using namespace std;
class MyHashSet {
public:
vector<list<int>> Hashmap;//使用链表解决冲突
static const int Base = 769;
static int hashfunc(int num){
return num%Base;
}
MyHashSet():Hashmap(Base) {
}
void add(int key) {
int h = hashfunc(key);
for(auto it = Hashmap[h].begin();it!=Hashmap[h].end();it++){
if((*it)==key){
return;
}
}
Hashmap[h].push_back(key);
}
void remove(int key) {
int h = hashfunc(key);
for(auto it = Hashmap[h].begin();it!=Hashmap[h].end();i++){
if((*it)==key){
Hashmap[h].erase(it);//这个操作会使迭代器失效,要注意使用了erase以后不能继续操作迭代器了
return;
}
}
}
/** Returns true if this set contains the specified element */
bool contains(int key) {
int h = hashfunc(key);
for(auto it = Hashmap[h].begin();it!=Hashmap[h].end();i++){
if((*it)==key){
return true;
}
}
return false;
}
};
int main(){
MyHashSet myHashSet;
for(int i=0;i<10;i++)
{
myHashSet.add(i);
}
//这里开始自己调试
}