252. Meeting Rooms (Easy)
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]]
,
returnfalse
.
Solution 1: Arrays.sort O(n log n); O(1)
To determine if a person could attend all meetings, we need to check if the intervals have an overlap.
If an overlap exists, a person could not attend all meetings.
/**
* Sort intervals by start time.
* From second interval, check each interval with the previous one.
* If current interval's start < previous interval's end, which means an overlap exists, return false.
*/
public boolean canAttendMeetings(Interval[] intervals) {
if (intervals == null || intervals.length <= 1) {
return true;
}
// Arrays.sort(intervals, new Comparator<Interval>() {
// public int compare(Interval a, Interval b) {
// return a.start - b.start;
// }
// });
Arrays.sort(intervals, (a, b) -> a.start - b.start);
for (int i = 1; i < intervals.length; i++) {
if (intervals[i - 1].end > intervals[i].start) {
return false;
}
}
return true;
}
/**
* 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; }
* }
*/