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.

O(nlogn).

1
2
3
4
5
6
7
8
9
10
public class Solution {
public boolean canAttendMeetings(Interval[] intervals) {
// Sort the intervals by start time
Arrays.sort(intervals, (x, y) -> x.start - y.start);
for (int i = 1; i < intervals.length; i++)
if (intervals[i-1].end > intervals[i].start)
return false;
return true;
}
}

The following solution is cited from Leetcode Discussion board.

####Find an overlap while sorting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private boolean canAttendMeetings(Interval[] intervals) {
try {
Arrays.sort(intervals, new IntervalComparator());
} catch (Exception e) {
return false;
}
return true;
}

private class IntervalComparator implements Comparator<Interval> {
@Override
public int compare(Interval o1, Interval o2) {
if (o1.start < o2.start && o1.end <= o2.start)
return -1;
else if (o1.start > o2.start && o1.start >= o2.end)
return 1;
throw new RuntimeException();
}
}