Repository navigation
Expand file tree
/
Copy pathMyHashMap.py
More file actions
51 lines (44 loc) · 1.48 KB
/
Copy pathMyHashMap.py
File metadata and controls
51 lines (44 loc) · 1.48 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
class MyHashMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.hash_map = [None] * 1000
def put(self, key, value):
"""
value will always be non-negative.
:type key: int
:type value: int
:rtype: None
"""
the_hash = hash(key) % 1000
if not self.hash_map[the_hash]:
self.hash_map[the_hash] = []
self.remove(key)
self.hash_map[the_hash].append((key, value))
def get(self, key):
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
:type key: int
:rtype: int
"""
the_hash = hash(key) % 1000
if self.hash_map[the_hash]:
for t in self.hash_map[the_hash]:
if t[0] == key:
return t[1]
return -1
def remove(self, key):
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
:type key: int
:rtype: None
"""
the_hash = hash(key) % 1000
to_delete = None
if self.hash_map[the_hash]:
new_cell = []
for i in range(len(self.hash_map[the_hash])):
if not self.hash_map[the_hash][i][0] == key:
new_cell.append(self.hash_map[the_hash][i])
self.hash_map[the_hash] = new_cell