-
Notifications
You must be signed in to change notification settings - Fork 0
/
design_HashMap.py
113 lines (92 loc) · 2.53 KB
/
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# Using Linked-List
class ListNode(object):
def __init__(self, key, value):
self.pair = (key, value)
self.next = None
class MyHashMap(object):
def __init__(self):
self.length = 1000
self.table = [None] * self.length
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
index = key % self.length
if self.table[index] == None:
self.table[index] = ListNode(key, value)
else:
curr = self.table[index]
while True:
if curr.pair[0] == key:
curr.pair = (key, value)
return
if curr.next == None:
curr.next = ListNode(key, value)
return
curr = curr.next
def get(self, key):
"""
:type key: int
:rtype: int
"""
index = key % self.length
curr = self.table[index]
while curr:
if curr.pair[0] == key:
return curr.pair[1]
curr = curr.next
return -1
def remove(self, key):
"""
:type key: int
:rtype: None
"""
index = key % self.length
curr = self.table[index]
if curr == None:
return
if curr.pair[0] == key:
self.table[index] = curr.next
return
prev = curr
curr = curr.next
while curr:
if curr.pair[0] == key:
prev.next = curr.next
return
curr = curr.next
prev = prev.next
# Using List
class MyHashMap(object):
def __init__(self):
self.key = []
self.val = []
def put(self, key, value):
if key in self.key:
idx = self.key.index(key)
self.val[idx] = value
else:
self.key.append(key)
self.val.append(value)
def get(self, key):
if key in self.key:
idx = self.key.index(key)
return self.val[idx]
return -1
def remove(self, key):
if key in self.key:
idx = self.key.index(key)
self.key.pop(idx)
self.val.pop(idx)
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.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)