0705.cpp (955B)
1 class MyHashSet { 2 class Node { 3 public: 4 int val; 5 Node *next; 6 7 Node() : val(-1), next(nullptr) {} 8 Node(int val, Node *next) : val(val), next(next) {} 9 }; 10 11 static constexpr int SIZE = 10007; 12 Node bucket[SIZE] = {}; 13 14 int hash(int key) { return key % SIZE; } 15 16 public: 17 MyHashSet() {} 18 19 void add(int key) { 20 if (contains(key)) return; 21 Node *b = &bucket[hash(key)]; 22 b->next = new Node(key, b->next); 23 } 24 25 void remove(int key) { 26 Node *prev = &bucket[hash(key)], *crnt = prev->next; 27 while (crnt && crnt->val != key) { 28 prev = crnt; 29 crnt = crnt->next; 30 } 31 if (!crnt) return; 32 prev->next = crnt->next; 33 delete crnt; 34 } 35 36 bool contains(int key) { 37 for (Node *crnt = bucket[hash(key)].next; crnt; crnt = crnt->next) 38 if (crnt->val == key) return true; 39 return false; 40 } 41 };