- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 40 lines of C++ from the credited upstream file 1847.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 3 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> closestRoom(vector<vector<int>>& rooms,4 vector<vector<int>>& queries) {5 vector<int> ans(queries.size());6 set<int> roomIds;7 8 for (int i = 0; i < queries.size(); ++i)9 queries[i].push_back(i);10 11 ranges::sort(rooms, ranges::greater{},12 [](const vector<int>& room) { return room[1]; });13 ranges::sort(queries, ranges::greater{},14 [](const vector<int>& query) { return query[1]; });15 16 int i = 0; 17 for (const vector<int>& query : queries) {18 while (i < rooms.size() && rooms[i][1] >= query[1])19 roomIds.insert(rooms[i++][0]);20 ans[query[2]] = searchClosestRoomId(roomIds, query[0]);21 }22 23 return ans;24 }25 26 private:27 int searchClosestRoomId(set<int>& roomIds, int preferred) {28 const auto it = roomIds.lower_bound(preferred);29 const int id1 = it == roomIds.cbegin() ? -1 : *(prev(it));30 const int id2 = it == roomIds.cend() ? -1 : *it;31 if (id1 == -1)32 return id2;33 if (id2 == -1)34 return id1;35 if (abs(preferred - id1) <= abs(preferred - id2))36 return id1;37 return id2;38 }39};40