# 2402. Meeting Rooms III ###### tags: `Leetcode` `Hard` `Priority Queue` Link: https://leetcode.com/problems/meeting-rooms-iii/ ## 思路 ```unused``` contains the ready room index for meetings. ```rooms``` contains the rooms in use with ```[end_time, room_index]``` as element. For ```[start, end]``` in the sorted ```meetings```, we firstly release the rooms that is ready before ```start``` time. If there is room in ```ready``` state, we choose the room with smallest index. Otherwise, we choose the room with smallest ```end_time``` in ```rooms```. ## Code ```java= class Solution { public int mostBooked(int n, int[][] meetings) { Arrays.sort(meetings, (a,b)->(a[0]-b[0])); Queue<Integer> unused = new PriorityQueue<>(); for (int i=0; i<n; i++) unused.add(i); PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> { if (a[0] == b[0]) return a[1] - b[1]; return (a[0] - b[0]); }); int[] count = new int[n]; int maxFreq = 0; for (int[] meeting:meetings) { while (!pq.isEmpty() && meeting[0] >= pq.peek()[0]) { unused.add(pq.poll()[1]); } int room; if (!unused.isEmpty()) { room = unused.poll(); count[room]++; pq.add(new int[]{meeting[1], room}); } else { int[] last = pq.poll(); int delayed = last[0]; room = last[1]; int curEnd = delayed + meeting[1] - meeting[0]; count[room]++; pq.add(new int[]{curEnd, room}); } maxFreq = Math.max(count[room], maxFreq); } for (int i = 0; i < n; i++) { if(count[i]==maxFreq) return i; } return 0; } }- ```