design hashset

This commit is contained in:
2022-04-22 09:48:40 +05:30
parent fb6e386479
commit f819e84c32
2 changed files with 79 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
from collections import deque
class MyHashSet:
def __init__(self):
self.hashDivisor = 769 # Pick a prime number to avoid collisions
self.buckets = [Bucket() for _ in range(self.hashDivisor)]
def add(self, key: int) -> None:
hash = self.hash(key)
self.buckets[hash].add(key)
def remove(self, key: int) -> None:
hash = self.hash(key)
self.buckets[hash].remove(key)
def contains(self, key: int) -> bool:
hash = self.hash(key)
return self.buckets[hash].contains(key)
def hash(self, key: int) -> int:
return key % self.hashDivisor
class Bucket:
def __init__(self):
self.d = deque()
pass
def add(self, key: int) -> None:
if key not in self.d:
self.d.append(key)
def remove(self, key: int) -> None:
try:
self.d.remove(key)
except:
pass
def contains(self, key: int) -> None:
return key in self.d
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)