-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path706. Design HashMap.py
More file actions
63 lines (53 loc) · 1.86 KB
/
706. Design HashMap.py
File metadata and controls
63 lines (53 loc) · 1.86 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Bucket:
def __init__(self):
self.bucket = []
def get(self, key):
for (k,v) in self.bucket:
if k == key:
return v
return -1
def update(self, key, value):
found = False
for i, kv in enumerate(self.bucket):
if key == kv[0]:
self.bucket[i] = (key, value)
found = True
break
# Try taking away found, replacing break with return,
# and taking away if not found from the def update method
if not found:
self.bucket.append((key,value))
def remove(self, key):
for i, kv in enumerate(self.bucket):
if key == kv[0]:
del self.bucket[i]
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.key_space = 2069
self.hash_table = [Bucket() for i in range(self.key_space)] #come back to this
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
hash_key = key % self.key_space
self.hash_table[hash_key].update(key,value)
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
"""
hash_key = key % self.key_space
return self.hash_table[hash_key].get(key)
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
hash_key = key % self.key_space
self.hash_table[hash_key].remove(key)
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)