题目:Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet. bool
contains(key) Returns whether the value key exists in the HashSet or
not. void remove(key) Removes the value key in the HashSet. If key
does not exist in the HashSet, do nothing.
class MyHashSet {
private:
//哈希散列和成员变量
vector<list<int>> vec;
static const int base = 888;
static int hash(int k){
return k % base;
}
public:
//init初始化
MyHashSet():vec(base) {}
//散列哈希,对哈希数组散列元素的列表集合添加无重复元素key
void add(int key) {
int a = hash(key);
//枚举数组i存储的列表
for(auto it = vec[a].begin();it != vec[a].end();it++){
//相同元素返回
if((*it) == key){return;}
}
vec[a].push_back(key);
}
//散列哈希,对哈希数组散列元素的列表集合删除无重复元素key
void remove(int key) {
int a = hash(key);
//枚举数组i存储的列表
for(auto it = vec[a].begin();it != vec[a].end();it++){
//遇到key相同元素,删除
if((*it) == key){
vec[a].erase(it);
return;
}
}
}
//散列哈希,对哈希数组散列元素的列表集合是否包含无重复元素key
bool contains(int key) {
int a = hash(key);
//枚举数组i存储的列表
for(auto it = vec[a].begin();it != vec[a].end();it++){
//找到key,返回真
if((*it) == key){
return true;
}
}
return false;
}
};
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet* obj = new MyHashSet();
* obj->add(key);
* obj->remove(key);
* bool param_3 = obj->contains(key);
*/