Skip to content

Commit a965ba9

Browse files
HashSet
1 parent db0e0d1 commit a965ba9

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

HashSet.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class HashSet:
2+
def __init__(self, n=1000):
3+
"""
4+
Initialize your data structure here.
5+
"""
6+
self.n = n
7+
self.key_value = list()
8+
for idx in range(self.n):
9+
self.key_value.append([idx])
10+
11+
def _hash(self, value):
12+
return value % self.n
13+
14+
def add(self, value):
15+
"""
16+
:type value: int
17+
:rtype: void
18+
"""
19+
hash_value = self._hash(value)
20+
if self.contains(value):
21+
print("Duplicate Insert of {0}".format(value))
22+
else:
23+
self.key_value[hash_value].append(value)
24+
25+
def remove(self, value):
26+
"""
27+
:type value: int
28+
:rtype: void
29+
"""
30+
hash_value = self._hash(value)
31+
if self.contains(value):
32+
self.key_value[hash_value].remove(value)
33+
else:
34+
print("{0} is not present in the HashSet.".format(value))
35+
36+
def contains(self, value):
37+
"""
38+
Returns true if this set contains the specified element
39+
:type value: int
40+
:rtype: bool
41+
"""
42+
hash_value = self._hash(value)
43+
if value in self.key_value[hash_value][1:]:
44+
return True
45+
else:
46+
return False
47+
48+
'''
49+
# Your MyHashSet object will be instantiated and called as such:
50+
obj = HashSet()
51+
obj.add(1)
52+
obj.add(1001)
53+
obj.remove(1)
54+
param_3 = obj.contains(1001)
55+
print(param_3)
56+
'''

0 commit comments

Comments
 (0)