-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path705. Design HashSet.py
More file actions
43 lines (31 loc) · 978 Bytes
/
705. Design HashSet.py
File metadata and controls
43 lines (31 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class MyHashSet:
def __init__(self):
self.size = 10000
self.buckets = [[] for _ in range(self.size)]
def add(self, key: int) -> None:
bucket, idx = self._index(key)
if idx >= 0:
return
bucket.append(key)
def remove(self, key: int) -> None:
bucket, idx = self._index(key)
if idx < 0:
return
bucket.remove(key)
def contains(self, key: int) -> bool:
_, idx = self._index(key)
return idx >= 0
def _hash(self, key):
return key % self.size
def _index(self, key):
hash = self._hash(key)
bucket = self.buckets[hash]
for i, k in enumerate(bucket):
if k == key:
return bucket, i
return bucket, -1
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)