Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f789525

Browse files
authoredNov 29, 2023
Update 1847-closest-room.js
1 parent 09e6ece commit f789525

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
 

‎1847-closest-room.js

+50
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,53 @@
1+
/**
2+
* @param {number[][]} rooms
3+
* @param {number[][]} queries
4+
* @return {number[]}
5+
*/
6+
var closestRoom = function (rooms, queries) {
7+
const n = rooms.length
8+
const k = queries.length
9+
const indexes = new Array(k)
10+
for (let i = 0; i < k; i++) {
11+
indexes[i] = i
12+
}
13+
rooms.sort((a, b) => b[1] - a[1]) // Sort by decreasing order of room size
14+
indexes.sort((a, b) => queries[b][1] - queries[a][1]) // Sort by decreasing order of query minSize
15+
const roomIdsSoFar = new Set()
16+
const ans = new Array(k)
17+
let i = 0
18+
for (const index of indexes) {
19+
while (i < n && rooms[i][1] >= queries[index][1]) {
20+
// Add id of the room which its size >= query minSize
21+
roomIdsSoFar.add(rooms[i++][0])
22+
}
23+
ans[index] = searchClosetRoomId(roomIdsSoFar, queries[index][0])
24+
if (ans[index] == Infinity || ans[index] == -Infinity) ans[index] = -1
25+
}
26+
return ans
27+
28+
function searchClosetRoomId(treeSet, preferredId) {
29+
let floor = -Infinity
30+
let ceiling = Infinity
31+
for (const id of treeSet) {
32+
if (id <= preferredId) {
33+
floor = Math.max(floor, id)
34+
} else {
35+
ceiling = Math.min(ceiling, id)
36+
}
37+
}
38+
if (floor === -Infinity) {
39+
return ceiling
40+
} else if (ceiling === Infinity) {
41+
return floor
42+
} else if (preferredId - floor <= ceiling - preferredId) {
43+
return floor
44+
} else {
45+
return ceiling
46+
}
47+
}
48+
}
49+
50+
// another
151

252
/**
353
* @param {number[][]} rooms

0 commit comments

Comments
 (0)
Please sign in to comment.