题目
思路
用链表模拟,可以取769(看的官方)为最大,也可以直接开个大数组也能过
代码语言:javascript复制class MyHashSet {
public:
vector<list<int>> mp;
const int base = 769;
int hash(int n) {
return n % base;
}
/** Initialize your mp structure here. */
MyHashSet() {
mp = vector<list<int>>(base);
}
void add(int key) {
int m = hash(key);
for (auto it = mp[m].begin(); it != mp[m].end(); it ) {
if ((*it) == key) return;
}
mp[m].push_back(key);
}
void remove(int key) {
int m = hash(key);
for (auto it = mp[m].begin(); it != mp[m].end(); it ) {
if ((*it) == key) {
mp[m].erase(it);
return;
}
}
}
/** Returns true if this set contains the specified element */
bool contains(int key) {
int m = hash(key);
for (auto it = mp[m].begin(); it != mp[m].end(); it ) {
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);
*/