[LeetCode] Closest Room

1847. Closest Room

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 least minSizej, 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 array answer of length k where answer[j] contains the answer to the jth query.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
vector<int> closestRoom(vector<vector<int>>& R, vector<vector<int>>& q) {
vector<array<int,3>> Q;
for(int i = 0; i < q.size(); i++) {
Q.push_back({q[i][1], q[i][0], i});
}
sort(begin(Q), end(Q));
sort(begin(R), end(R), [](vector<int>& a, vector<int>& b) {return a[1] < b[1];});

vector<int> res(Q.size());
set<int> id;
for(int i = Q.size() - 1, j = R.size() - 1; i >= 0; i--) {
auto [msz, pref, qid] = Q[i];
while(j >= 0 and R[j][1] >= msz) id.insert(R[j--][0]);

if(id.empty()) res[qid] = -1;
else {
int gap = INT_MAX, pick = -1;
auto it = id.lower_bound(pref);
if(it != end(id))
gap = *it - pref, pick = *it;
if(it != begin(id)) {
it = prev(it);
if(gap >= pref - *it)
pick = *it;
}

res[qid] = pick;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/14/PS/LeetCode/closest-room/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.