Skip to content

Commit ae651b0

Browse files
authored
Update closest-room.py
1 parent 2fed310 commit ae651b0

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Python/closest-room.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,41 @@ def find_closest(ids, r):
3535
i += 1
3636
result[idx] = find_closest(ids, r)
3737
return result
38+
39+
40+
# Time: O(nlogn + klogk + klogn)
41+
# Space: O(n + k)
42+
from sortedcontainers import SortedList
43+
44+
45+
class Solution2(object):
46+
def closestRoom(self, rooms, queries):
47+
"""
48+
:type rooms: List[List[int]]
49+
:type queries: List[List[int]]
50+
:rtype: List[int]
51+
"""
52+
def find_closest(ids, r):
53+
result, min_dist = -1, float("inf")
54+
i = ids.bisect_right(r)
55+
if i-1 >= 0 and abs(ids[i-1]-r) < min_dist:
56+
min_dist = abs(ids[i-1]-r)
57+
result = ids[i-1]
58+
if i < len(ids) and abs(ids[i]-r) < min_dist:
59+
min_dist = abs(ids[i]-r)
60+
result = ids[i]
61+
return result
62+
63+
rooms.sort(key=lambda x: x[1])
64+
for i, q in enumerate(queries):
65+
q.append(i)
66+
queries.sort(key=lambda x: x[1])
67+
ids = SortedList(i for i, _ in rooms)
68+
i = 0
69+
result = [-1]*len(queries)
70+
for r, s, idx in queries:
71+
while i < len(rooms) and rooms[i][1] < s:
72+
ids.remove(rooms[i][0])
73+
i += 1
74+
result[idx] = find_closest(ids, r)
75+
return result

0 commit comments

Comments
 (0)