Leetcode - Meeting rooms solution in Java
Meeting Rooms
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.
For example, Given [[0, 30],[5, 10],[15, 20]], return false.
Analysis
We can sort the intervals using the start time. Then we check whether there is conflict. For instance. for this two pairs, [0, 30],[5, 10] As 5 is smaller than 30, the person cannot attend both.
When we do the check, we should record the latest end time before the current interval. For current interval, if it is less than the latestEndTime, we return False.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class MeetingRooms { public boolean canAttendMeetings(Interval[] intervals) { if(intervals == null || intervals.length == 0) return true; Arrays.sort(intervals, new Comparator<T>(){ public int compare(Interval ia, Interval ib){ return ia.start - ib.start; } }); int latestEnd = intervals[0].end; for(int i = 1; i < intervals.length; i++){ if(intervals[i].start < latestEnd) return false; latestEnd = Math.max(latestEnd, intervals[i].end); } return true; } } |











