Approach
Sorting and greedy selection
For Closest Room, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 37 lines of Java from the credited upstream file 1847.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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 int[] closestRoom(int[][] rooms, int[][] queries) {3 int[] ans = new int[queries.length];4 Integer[] indices = new Integer[queries.length];5 TreeSet<Integer> roomIds = new TreeSet<>();6 7 for (int i = 0; i < queries.length; ++i)8 indices[i] = i;9 10 Arrays.sort(rooms, Comparator.comparingInt(room -> - room[1]));11 Arrays.sort(indices, Comparator.comparingInt(index -> - queries[index][1]));12 13 int i = 0; 14 for (final int index : indices) {15 while (i < rooms.length && rooms[i][1] >= queries[index][1])16 roomIds.add(rooms[i++][0]);17 ans[index] = searchClosestRoomId(roomIds, queries[index][0]);18 }19 20 return ans;21 }22 23 private int searchClosestRoomId(TreeSet<Integer> roomIds, int preferred) {24 Integer floor = roomIds.floor(preferred);25 Integer ceiling = roomIds.ceiling(preferred);26 final int id1 = floor == null ? -1 : floor;27 final int id2 = ceiling == null ? -1 : ceiling;28 if (id1 == -1)29 return id2;30 if (id2 == -1)31 return id1;32 if (Math.abs(preferred - id1) <= Math.abs(preferred - id2))33 return id1;34 return id2;35 }36}37