题目链接:https://leetcode-cn.com/problems/design-hashset/
题目如下:
class MyHashSet {
public:
//有一个大小为N的数组vector,数组的每个位置是一个链表list(双链表)
MyHashSet():data(N){}//构造函数初始化的一种方式
void add(int key) {
int t=hash(key);//计算哈希值
for(auto it=data[t].begin();it!=data[t].end();it++){//遍历这个数组位置从链表开始到末尾,有无数值的存在
if((*it)==key) return;//it为迭代器,即指针指向的地址,*即取地址中的数值
}
data[t].push_back(key);
}
void remove(int key) {
int t=hash(key);
for(auto it=data[t].begin();it!=data[t].end();it++){
if((*it)==key){
data[t].erase(it);
return;
}
}
}
bool contains(int key) {
int t=hash(key);
for(auto it=data[t].begin();it!=data[t].end();it++){
if((*it)==key) return true;
}
return false;
}
private:
vector<list<int>> data;
static const int N=100010;
static int hash(int key){
return key%N;
}
};
/**
* 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);
*/