C++  code || Easy to understand and implement || Beats in Runtime and Memory
\n\n# Approach\n Describe your approach to solving the problem. Try out this way!\n\n# Complexity\n- Time complexity: O(sort(n)+sort(q)+qlogn)\n Add your time c
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->Try out this way!\n\n# Complexity\n- Time complexity: O(sort(n)+sort(q)+qlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n+q)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public:\n  vector<int> closestRoom(vector<vector<int>>& rooms,\n                          vector<vector<int>>& queries) {\n    vector<int> ans(queries.size());\n    set<int> roomIds;\n\n    for (int i = 0; i < queries.size(); ++i)\n      queries[i].push_back(i);\n\n    auto descSize = [](const auto& a, const auto& b) { return a[1] > b[1]; };\n    sort(rooms.begin(), rooms.end(), descSize);\n    sort(queries.begin(), queries.end(), descSize);\n\n    int i = 0;  // rooms\' pointer\n    for (const vector<int>& query : queries) {\n      while (i < rooms.size() && rooms[i][1] >= query[1])\n        roomIds.insert(rooms[i++][0]);\n      ans[query[2]] = searchClosestRoomId(roomIds, query[0]);\n    }\n\n    return ans;\n  }\n\n private:\n  int searchClosestRoomId(set<int>& roomIds, int preferred) {\n    const auto it = roomIds.lower_bound(preferred);\n    const int id1 = it == roomIds.cbegin() ? -1 : *(prev(it));\n    const int id2 = it == roomIds.cend() ? -1 : *it;\n    if (id1 == -1)\n      return id2;\n    if (id2 == -1)\n      return id1;\n    if (abs(preferred - id1) <= abs(preferred - id2))\n      return id1;\n    return id2;\n  }\n};\n\n```
['C++']