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.
Example 1:
1
Input:
2
[[0,30],[5,10],[15,20]]
3
Output:
4
false
Copied!
Example 2:
1
Input:
2
[[7,10],[2,4]]
3
4
Output:
5
true
Copied!

Solution & Analysis

The idea here is to sort the meetings by starting time. Then, go through the meetings one by one and make sure that each meeting ends before the next one starts.
  • Time complexity : O(nlogn). The time complexity is dominated by sorting. Once the array has been sorted, only O(n) time is taken to go through the array and determine if there is any overlap.
  • Space complexity : O(1). Since no additional space is allocated.
先排序,再遍历
Sort, then compare last.end vs. current.start; similar to Merge Intervals
1
/**
2
* Definition for an interval.
3
* public class Interval {
4
* int start;
5
* int end;
6
* Interval() { start = 0; end = 0; }
7
* Interval(int s, int e) { start = s; end = e; }
8
* }
9
*/
10
class Solution {
11
public boolean canAttendMeetings(Interval[] intervals) {
12
Arrays.sort(intervals, new Comparator<Interval>() {
13
public int compare(Interval i1, Interval i2) {
14
return i1.start - i2.start;
15
}
16
});
17
Interval last = null;
18
for (Interval i: intervals) {
19
if (last != null && i.start < last.end) {
20
return false;
21
}
22
last = i;
23
}
24
return true;
25
}
26
}
Copied!
Sorting
1
public boolean canAttendMeetings(Interval[] intervals) {
2
Arrays.sort(intervals, new Comparator<Interval>() {
3
public int compare(Interval i1, Interval i2) {
4
return i1.start - i2.start;
5
}
6
});
7
for (int i = 0; i < intervals.length - 1; i++) {
8
if (intervals[i].end > intervals[i + 1].start) return false;
9
}
10
return true;
11
}
Copied!
Other implementation
Sorting - throw expection
1
private boolean canAttendMeetings(Interval[] intervals) {
2
try {
3
Arrays.sort(intervals, new IntervalComparator());
4
} catch (Exception e) {
5
return false;
6
}
7
return true;
8
}
9
10
private class IntervalComparator implements Comparator<Interval> {
11
@Override
12
public int compare(Interval o1, Interval o2) {
13
if (o1.start < o2.start && o1.end <= o2.start)
14
return -1;
15
else if (o1.start > o2.start && o1.start >= o2.end)
16
return 1;
17
throw new RuntimeException();
18
}
19
}
Copied!
Java 8
1
public boolean canAttendMeetings(Interval[] intervals) {
2
// Sort the intervals by start time
3
Arrays.sort(intervals, (x, y) -> x.start - y.start);
4
for (int i = 1; i < intervals.length; i++)
5
if (intervals[i-1].end > intervals[i].start)
6
return false;
7
return true;
8
}
Copied!

Reference

Last modified 1yr ago