-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path88.py
More file actions
40 lines (30 loc) · 1.26 KB
/
88.py
File metadata and controls
40 lines (30 loc) · 1.26 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
from collections import defaultdict
import heapq
class NumberContainers:
def __init__(self):
# Map to store number -> min heap of indices
self.number_to_indices = defaultdict(list)
# Map to store index -> number
self.index_to_numbers = {}
def change(self, index: int, number: int) -> None:
# Update index to number mapping
self.index_to_numbers[index] = number
# Add index to the min heap for this number
heapq.heappush(self.number_to_indices[number], index)
def find(self, number: int) -> int:
# If number doesn't exist in our map
if not self.number_to_indices[number]:
return -1
# Keep checking top element until we find valid index
while self.number_to_indices[number]:
index = self.number_to_indices[number][0]
# If index still maps to our target number, return it
if self.index_to_numbers.get(index) == number:
return index
# Otherwise remove this stale index
heapq.heappop(self.number_to_indices[number])
return -1
# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)