leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0705.cpp (955B)


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