Untitled
import java.util.*; class Interval { int start; int end; Interval(int start, int end) { this.start = start; this.end = end; } } public class Solution { public int minMeetingRooms(List<Interval> intervals) { if (intervals == null || intervals.isEmpty()) { return 0; // No intervals, no rooms needed } // Separate start and end times into two arrays int n = intervals.size(); int[] startTimes = new int[n]; int[] endTimes = new int[n]; for (int i = 0; i < n; i++) { startTimes[i] = intervals.get(i).start; endTimes[i] = intervals.get(i).end; } // Sort both arrays Arrays.sort(startTimes); Arrays.sort(endTimes); int count = 0; // Current number of meeting rooms needed int maxRooms = 0; // Maximum number of rooms needed int i = 0, j = 0; // Use two pointers to traverse the start and end times while (i < n) { // If a meeting is starting, increment count if (startTimes[i] < endTimes[j]) { count++; maxRooms = Math.max(maxRooms, count); i++; } // If a meeting is ending, decrement count else { count--; j++; } } return maxRooms; // Return the maximum number of rooms needed } public static void main(String[] args) { List<Interval> intervals1 = Arrays.asList( new Interval(0, 40), new Interval(5, 10), new Interval(15, 20) ); Solution solution = new Solution(); System.out.println("Output 1: " + solution.minMeetingRooms(intervals1)); // Output: 2 List<Interval> intervals2 = Arrays.asList( new Interval(4, 9) ); System.out.println("Output 2: " + solution.minMeetingRooms(intervals2)); // Output: 1 List<Interval> intervals3 = Arrays.asList( new Interval(0, 8), new Interval(8, 10) ); System.out.println("Output 3: " + solution.minMeetingRooms(intervals3)); // Output: 1 } }
Leave a Comment