|
| 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 |
1 | 51 |
|
2 | 52 | /**
|
3 | 53 | * @param {number[][]} rooms
|
|
0 commit comments