|
| 1 | +import java.util.Arrays; |
| 2 | +import java.util.Comparator; |
| 3 | +import java.util.TreeSet; |
| 4 | + |
| 5 | +// https://leetcode.com/contest/biweekly-contest-51/problems/closest-room/ |
| 6 | + |
| 7 | +public class ClosestRoom { |
| 8 | + |
| 9 | + // We sort queries by the decreasing of its minSize order. |
| 10 | + // We sort rooms by the decreasing of its size order. |
| 11 | + // We initialize roomIdsSoFar TreeSet, |
| 12 | + // this includes all room ids which have size >=minSize of current query so far. |
| 13 | + // For each query: |
| 14 | + // - Add all room ids which have size >=minSize of current query. |
| 15 | + // - Query floor and ceiling of q[0] (preferredId) from roomIdsSoFar |
| 16 | + // to pick the id which closest to our preferredId |
| 17 | + |
| 18 | + // online query processing |
| 19 | + // floor and ceiling operate in O(logN) |
| 20 | + // TC: O(NlogN + KlogK + KlogN) |
| 21 | + // SC: O(N + K) |
| 22 | + public int[] closestRoom(int[][] rooms, int[][] queries) { |
| 23 | + Integer[] indices = new Integer[queries.length]; |
| 24 | + for (int i = 0; i < queries.length; i++) { |
| 25 | + indices[i] = i; |
| 26 | + } |
| 27 | + // Sort by decreasing order of room size |
| 28 | + Arrays.sort(rooms, Comparator.comparingInt(a -> a[1])); |
| 29 | + // Sort by decreasing order of query minSize |
| 30 | + Arrays.sort(indices, (a, b) -> Integer.compare(queries[b][1], queries[a][1])); |
| 31 | + TreeSet<Integer> roomIdsSoFar = new TreeSet<>(); |
| 32 | + int[] result = new int[queries.length]; |
| 33 | + int id = 0; |
| 34 | + for (int index : indices) { |
| 35 | + // Add id of the room when its size >= query minSize |
| 36 | + while (id < rooms.length && rooms[id][1] >= queries[index][1]) { |
| 37 | + roomIdsSoFar.add(rooms[id++][0]); |
| 38 | + } |
| 39 | + result[index] = searchClosetRoomId(roomIdsSoFar, queries[index][0]); |
| 40 | + } |
| 41 | + return result; |
| 42 | + } |
| 43 | + |
| 44 | + private int searchClosetRoomId(TreeSet<Integer> roomIdsSoFar, int preferredId) { |
| 45 | + Integer floor = roomIdsSoFar.floor(preferredId); |
| 46 | + Integer ceiling = roomIdsSoFar.ceiling(preferredId); |
| 47 | + int k = Integer.MAX_VALUE; |
| 48 | + int closestRoomId = -1; |
| 49 | + if (floor != null) { |
| 50 | + closestRoomId = floor; |
| 51 | + k = Math.abs(preferredId - floor); |
| 52 | + } |
| 53 | + if (ceiling != null) { |
| 54 | + if (k > Math.abs(preferredId - ceiling)) { |
| 55 | + closestRoomId = ceiling; |
| 56 | + } |
| 57 | + } |
| 58 | + return closestRoomId; |
| 59 | + } |
| 60 | +} |
0 commit comments