-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0706-design-hashmap.py
36 lines (31 loc) · 1.01 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
class ListNode:
def __init__(self, key=-1, val=-1, next=None):
self.key = key
self.val = val
self.next = next
class MyHashMap:
def __init__(self):
self.map = [ListNode() for i in range(1000)]
def hashcode(self, key):
return key % len(self.map)
def put(self, key: int, value: int) -> None:
cur = self.map[self.hashcode(key)]
while cur.next:
if cur.next.key == key:
cur.next.val = value
return
cur = cur.next
cur.next = ListNode(key, value)
def get(self, key: int) -> int:
cur = self.map[self.hashcode(key)].next
while cur and cur.key != key:
cur = cur.next
if cur:
return cur.val
return -1
def remove(self, key: int) -> None:
cur = self.map[self.hashcode(key)]
while cur.next and cur.next.key != key:
cur = cur.next
if cur and cur.next:
cur.next = cur.next.next