forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashmap_aishwarya_l.py
73 lines (60 loc) · 1.89 KB
/
hashmap_aishwarya_l.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
63
64
65
66
67
68
69
70
71
72
73
"""
The time complexity for all operations if O(n) where n is the size of linked_list attached to the primary array
Space complexity is O(n)
"""
from lib2to3.pytree import Node
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = Node
class MyHashMap:
def __init__(self):
self.buckets = 10000
self.nodes = [Node for i in range(self.buckets)]
def hash_one(self, key: int):
return self.buckets%key
def find(self, head: Node, key: int):
prev = head
curr = head.next
while curr is not None and curr.key is not key:
prev = curr
curr = curr.next
return prev
def put(self, key: int, value: int) -> None:
primary_index = self.hash_one(key)
if self.nodes[primary_index] is None:
self.nodes[primary_index] = Node(-1, -1)
prev_node = self.find(self.nodes[primary_index], key)
if prev_node is None:
prev_node.next = Node(key, value)
else:
prev_node.next_node.value = value
def get(self, key: int) -> int:
primary_index = self.hash_one(key)
if self.nodes[primary_index] is None:
return -1
prev_node = self.find(self.nodes[primary_index], key)
if prev_node is None:
return -1
else:
prev_node.next.value
def remove(self, key: int) -> None:
primary_index = self.hash_one(key)
if self.nodes[primary_index] is None:
return
prev_node = self.find(self.nodes[primary_index], key)
if prev_node is None:
return
else:
prev_node.next.next
# Your MyHashMap object will be instantiated and called as such:
obj = MyHashMap()
obj.put(1,1)
obj.put(2,2)
print(obj.get(1))
print(obj.get(3))
obj.put(2,1)
print(obj.get(2))
print(obj.remove(2))
print(obj.get(2))