1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import java.util.*; public class Solution { public static int minMeetingRooms(int[][] intervals) { // Store end times of each room Queue<Integer> minHeap = new PriorityQueue<>(); Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); // O(nlogn) /*Java 8 (a, b) -> Integer.compare(b[0],a[0])); //decreasing order (a, b) -> Integer.compare(a[0],b[0]); //increasing order */ System.out.println(Arrays.deepToString(intervals)); // [[0, 30], [5, 10], [15, 20]] for (int[] interval : intervals) { if (!minHeap.isEmpty() && interval[0] >= minHeap.peek()) // check head peek O(1) minHeap.poll(); // remove head, No overlap, we can reuse the same room O(logn) minHeap.offer(interval[1]); // insert offer O(logn) }
return minHeap.size(); // size is required room } public static void main(String[] args) { int[][] slot = {{15, 20}, {0, 30}, {5, 10}}; System.out.println(minMeetingRooms(slot)); } } > [[0, 30], [5, 10], [15, 20]] 2
|