48 lines
1.2 KiB
Python
48 lines
1.2 KiB
Python
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) |