There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. Each roomIdi is guaranteed to be unique.
You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The answer to the jth query is the room number id
of a room such that:
The room has a size of at leastminSizej, and
abs(id - preferredj) is minimized , where abs(x) is the absolute value of x.
If there is a tie in the absolute difference, then use the room with the
smallest such id. If there is no such room , the answer is -1.
Return an arrayanswerof lengthkwhereanswer[j]contains the answer to thejthquery.
Input: rooms =[[2,2],[1,2],[3,2]], queries =[[3,1],[3,3],[5,2]]Output: [3,-1,3]Explanation: The answers to the queries are as follows:Query =[3,1]: Room number 3is the closest as abs(3-3)=0, and its size of 2is at least 1. The answer is3.Query =[3,3]: There are no rooms with a size of at least 3, so the answer is-1.Query =[5,2]: Room number 3is the closest as abs(3-5)=2, and its size of 2is at least 2. The answer is3.
Input: rooms =[[1,4],[2,3],[3,5],[4,1],[5,2]], queries =[[2,3],[2,4],[2,5]]Output: [2,1,3]Explanation: The answers to the queries are as follows:Query =[2,3]: Room number 2is the closest as abs(2-2)=0, and its size of 3is at least 3. The answer is2.Query =[2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is1 since it is smaller.Query =[2,5]: Room number 3is the only room with a size of at least 5. The answer is3.
Sort the rooms by size (descending) and the queries by minSize (descending). As we process each query, we maintain a set of room IDs with sufficient size, allowing us to efficiently find the closest room ID to the preferred value using binary search.
classSolution {
funclosestRoom(rooms: Array<IntArray>, queries: Array<IntArray>): IntArray {
val k = queries.size
val qs = Array(k) { intArrayOf(queries[it][1], queries[it][0], it) }
rooms.sortByDescending { it[1] }
qs.sortByDescending { it[0] }
val ids = sortedSetOf<Int>()
val ans = IntArray(k) { -1 }
var j = 0for (q in qs) {
while (j < rooms.size && rooms[j][1] >= q[0]) ids.add(rooms[j++][0])
if (ids.isEmpty()) continueval hi = ids.ceiling(q[1])
val lo = ids.floor(q[1])
var res = -1; var diff = Int.MAX_VALUE
if (hi !=null&& kotlin.math.abs(hi - q[1]) < diff) { res = hi; diff = kotlin.math.abs(hi - q[1]) }
if (lo !=null&& (kotlin.math.abs(lo - q[1]) < diff || (kotlin.math.abs(lo - q[1]) == diff && lo < res))) res = lo
ans[q[2]] = res
}
return ans
}
}