1847. Closest Room Hard

@problem@discussion
#Array#Binary Search#Sorting



1/**
2 * [1847] Closest Room
3 *
4 * 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.
5 * You are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The answer to the j^th query is the room number id of a room such that:
6 * 
7 * 	The room has a size of at least minSizej, and
8 * 	abs(id - preferredj) is minimized, where abs(x) is the absolute value of x.
9 * 
10 * 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.
11 * Return an array answer of length k where answer[j] contains the answer to the j^th query.
12 *  
13 * Example 1:
14 * 
15 * Input: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]
16 * Output: [3,-1,3]
17 * Explanation: The answers to the queries are as follows:
18 * Query = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.
19 * Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.
20 * Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.
21 * Example 2:
22 * 
23 * Input: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]
24 * Output: [2,1,3]
25 * Explanation: The answers to the queries are as follows:
26 * Query = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.
27 * Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.
28 * Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.
29 *  
30 * Constraints:
31 * 
32 * 	n == rooms.length
33 * 	1 <= n <= 10^5
34 * 	k == queries.length
35 * 	1 <= k <= 10^4
36 * 	1 <= roomIdi, preferredj <= 10^7
37 * 	1 <= sizei, minSizej <= 10^7
38 * 
39 */
40pub struct Solution {}
41
42// problem: https://leetcode.com/problems/closest-room/
43// discuss: https://leetcode.com/problems/closest-room/discuss/?currentPage=1&orderBy=most_votes&query=
44
45// submission codes start here
46
47impl Solution {
48    pub fn closest_room(rooms: Vec<Vec<i32>>, queries: Vec<Vec<i32>>) -> Vec<i32> {
49        vec![]
50    }
51}
52
53// submission codes end
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_1847() {
61    }
62}
63


Back
© 2025 bowen.ge All Rights Reserved.