705. Design HashSet

class MyHashSet:def __init__(self):
self.array=[]
def add(self, key: int) -> None:
if(key not in self.array):
self.array.append(key)
def remove(self, key: int) -> None:
if(key in self.array):
for i in range(len(self.array)):
if(self.array[i]==key):
if(i==len(self.array)-1):
self.array=self.array[:i]
else:
self.array=self.array[:i]+self.array[i+1:]
break
else:
return(None)
def contains(self, key: int) -> bool:
if(key in self.array):
return True
return False
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)
class MyHashSet:
def __init__(self):
#number of buckets
#The load factor of the hash table should not cross 0.75
# Here the load factor is
# LF= number of entries / number of buckets
# 10^4/15000 = 0.666
self.buckets=15000
self.hashtable=[[] for i in range(self.buckets)]
def hash_function(self,key):
return(key%self.buckets)
def add(self, key: int) -> None:
index = self.hash_function(key)
if(key not in self.hashtable[index]):
self.hashtable[index].append(key)
def remove(self, key: int) -> None:
index = self.hash_function(key)
if(key in self.hashtable[index]):
self.hashtable[index].remove(key)
def contains(self, key: int) -> bool:
index = self.hash_function(key)
if(key in self.hashtable[index]):
return(True)
return(False)
class MyHashSet:

def __init__(self):
self.arr= [False] * (10**6 +1)

def add(self, key: int) -> None:
self.arr[key] = True

def remove(self, key: int) -> None:
self.arr[key] = False

def contains(self, key: int) -> bool:
return self.arr[key]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.