-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.py
More file actions
51 lines (46 loc) · 1.35 KB
/
solution.py
File metadata and controls
51 lines (46 loc) · 1.35 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 ListNode:
def __init__(self, key: int, val: int):
self.pair = (key, val)
self.next = None
class MyHashMap:
def __init__(self):
self.m = 2287
self.h = [None]*self.m
def put(self, key: int, value: int):
index = key % self.m
if self.h[index] == None:
self.h[index] = ListNode(key, value)
else:
cur = self.h[index]
while True:
if cur.pair[0] == key:
cur.pair = (key, value) # update
return
if cur.next == None:
break
cur = cur.next
cur.next = ListNode(key, value)
def get(self, key: int):
index = key % self.m
cur = self.h[index]
while cur:
if cur.pair[0] == key:
return cur.pair[1]
else:
cur = cur.next
return -1
def remove(self, key: int):
index = key % self.m
cur = prev = self.h[index]
if not cur:
return
if cur.pair[0] == key:
self.h[index] = cur.next
else:
cur = cur.next
while cur:
if cur.pair[0] == key:
prev.next = cur.next
break
else:
cur, prev = cur.next, prev.next