forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashmap.py
More file actions
67 lines (53 loc) · 1.71 KB
/
Hashmap.py
File metadata and controls
67 lines (53 loc) · 1.71 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
64
65
66
67
#// Time Complexity : Averge of O(1) unless everything ends up in one bucket.
#// Space Complexity : O(N)
#// Did this code successfully run on Leetcode : Yes
#// Any problem you faced while coding this : Had mutliple issues when converting theory concept to coding like referncing to one with 10000 copies of it.
#// Your code here along with comments explaining your approach
#using array of buckets and small list to store collions.
#used modulo function as hashing function to find key
class MyHashMap(object):
def __init__(self):
self.size = 1001
self.table = [[] for _ in range(self.size)]
def _hash(self,key):
return key % self.size
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
index = self._hash(key)
bucket = self.table[index]
for pair in bucket:
if pair[0] == key:
pair[1] = value
return
bucket.append([key,value])
def get(self, key):
"""
:type key: int
:rtype: int
"""
index = self._hash(key)
bucket = self.table[index]
for pair in bucket:
if pair[0] == key:
return pair[1]
return -1
def remove(self, key):
"""
:type key: int
:rtype: None
"""
index = self._hash(key)
bucket = self.table[index]
for i,pair in enumerate(bucket):
if pair[0] == key:
bucket.pop(i)
return
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)