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
return
Given
[[0, 30],[5, 10],[15, 20]]
,return
false
.Solution:
We first sort the intervals by their start.
If start equals, sort by end.
Then we go through the interval array and check the start of each interval.
If it is less than the previous interval's end, we know there is an overlap.
The time complexity is O(nlogn).
Code:
/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class Solution { public boolean canAttendMeetings(Interval[] intervals) { if (intervals == null || intervals.length == 0) { return true; } Arrays.sort(intervals, new Comparator<Interval>() { public int compare(Interval x, Interval y) { if (x.start == y.start) { return x.end - y.end; } return x.start - y.start; } }); for (int i = 1; i < intervals.length; i++) { if (intervals[i].start < intervals[i - 1].end) { return false; } } return true; } }