From fd46d87c6c2d61e27afb050ff9a453a3f0751a7d Mon Sep 17 00:00:00 2001 From: eat-swap Date: Thu, 21 Apr 2022 22:03:52 +0800 Subject: [PATCH] add: 220421-CN [cpp] --- cpp/2204/220421.cpp | 75 +++++++++++++++++++++++++++++++++++++++++ cpp/2204/CMakeLists.txt | 2 +- 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 cpp/2204/220421.cpp diff --git a/cpp/2204/220421.cpp b/cpp/2204/220421.cpp new file mode 100644 index 0000000..a324a0b --- /dev/null +++ b/cpp/2204/220421.cpp @@ -0,0 +1,75 @@ +struct Node { + int val; + Node* next; + + explicit Node(int x, Node* n) : val(x), next(n) {} +}; + +/** + * 705. Design HashSet + * Design a HashSet without using any built-in hash table libraries. + * Implement MyHashSet class: + * void add(key) Inserts the value key into the HashSet. + * bool contains(key) Returns whether the value key exists in the HashSet or not. + * void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing. + */ + +class MyHashSetNormal { +private: + static inline const int BUCKET_SIZE = 512; + + Node* bucket[BUCKET_SIZE] = {}; +public: + MyHashSetNormal() = default; + + void remove(int key) { + Node* ptr = this->bucket[key % BUCKET_SIZE]; + if (ptr && ptr->val == key) { + this->bucket[key % BUCKET_SIZE] = ptr->next; + delete ptr; + return; + } + for (; ptr && ptr->next; ptr = ptr->next) { + if (ptr->next->val == key) { + auto* toDelete = ptr->next; + ptr->next = toDelete->next; + delete toDelete; + } + } + } + + bool contains(int key) { + for (Node* ptr = this->bucket[key % BUCKET_SIZE]; ptr; ptr = ptr->next) + if (ptr->val == key) + return true; + return false; + } + + void add(int key) { + if (this->contains(key)) + return; + this->bucket[key % BUCKET_SIZE] = new Node(key, this->bucket[key % BUCKET_SIZE]); + } +}; + +#include + +// Slower... +class MyHashSet { +private: + std::bitset<1000001> s; +public: + MyHashSet() = default; + + void remove(int key) { + s.reset(key); + } + + bool contains(int key) { + return s.test(key); + } + + void add(int key) { + s.set(key); + } +}; diff --git a/cpp/2204/CMakeLists.txt b/cpp/2204/CMakeLists.txt index 5e03d09..23795a1 100644 --- a/cpp/2204/CMakeLists.txt +++ b/cpp/2204/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2204) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220421-CN.cpp) +ADD_EXECUTABLE(2204 220421.cpp)