-
Notifications
You must be signed in to change notification settings - Fork 1
/
0706-Design-HashMap.py
62 lines (51 loc) · 1.72 KB
/
0706-Design-HashMap.py
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
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.capacity = 100
self.internal_map = [[] for i in range(self.capacity)]
def hash_function(self, key):
return key % self.capacity
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
hash_key = self.hash_function(key)
bucket = self.internal_map[hash_key]
found = False
for i in range(len(bucket)):
if bucket[i][0] == key:
bucket[i][1] = value
found = True
break
if not found:
bucket.append([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 = self.hash_function(key)
bucket = self.internal_map[hash_key]
for i in range(len(bucket)):
if bucket[i][0] == key:
return bucket[i][1]
return -1
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 = self.hash_function(key)
bucket = self.internal_map[hash_key]
for i in range(len(bucket)):
if bucket[i][0] == key:
temp = bucket[i]
bucket[i] = bucket[0]
bucket[0] = temp
bucket.pop(0)
break
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)