classMyHashSet { private: vector<list<int>> hashSet; intgetHash(int &key){ return (key ^ (key >> 16)) % 13331; } public: //这里必须初始化vector,否则会导致空指针错误 MyHashSet(): hashSet(13331) {} voidadd(int key){ int h = getHash(key); for (auto it = hashSet[h].begin(); it != hashSet[h].end(); it++) { if (*it == key) return; } hashSet[h].emplace_front(key); }
voidremove(int key){ int h = getHash(key); for (auto it = hashSet[h].begin(); it != hashSet[h].end(); it++) { if (*it == key) { hashSet[h].erase(it); return; } } }
boolcontains(int key){ int h = getHash(key); for (auto it = hashSet[h].begin(); it != hashSet[h].end(); it++) { if (*it == key) { returntrue; } } returnfalse; } };