759 Employee Free Time

1. Question

We are given a listscheduleof employees, which represents the working time for each employee.
Each employee has a list of non-overlappingIntervals, and these intervals are in sorted order.
Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.
Example 1:
1
Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
2
3
Output: [[3,4]]
4
5
Explanation:
6
There are a total of three employees, and all common
7
free time intervals would be [-inf, 1], [3, 4], [10, inf].
8
We discard any intervals that contain inf as they aren't finite.
Copied!
Example 2:
1
Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
2
3
Output: [[5,6],[7,9]]
Copied!
(Even though we are representingIntervalsin the form[x, y], the objects inside areIntervals, not lists or arrays. For example,schedule[0][0].start = 1, schedule[0][0].end = 2, andschedule[0][0][0]is not defined.)
Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.
Note:
  1. 1.
    scheduleandschedule[i]are lists with lengths in range[1, 50].
  2. 2.
    0 <= schedule[i].start < schedule[i].end <= 10^8.

2. Implementation

(1) Heap
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 List<Interval> employeeFreeTime(List<List<Interval>> schedule) {
12
List<Interval> res = new ArrayList<>();
13
14
if (schedule == null || schedule.size() == 0) {
15
return res;
16
}
17
18
List<Interval> list = new ArrayList<>();
19
20
for (List<Interval> time : schedule) {
21
for (Interval interval : time) {
22
list.add(interval);
23
}
24
}
25
26
Collections.sort(list, new Comparator<Interval>() {
27
@Override
28
public int compare(Interval i1, Interval i2) {
29
return i1.start == i2.start ? i1.end - i2.end : i1.start - i2.start;
30
}
31
});
32
33
PriorityQueue<Integer> endTime = new PriorityQueue<>(Collections.reverseOrder());
34
endTime.add(list.get(0).end);
35
36
for (int i = 1; i < list.size(); i++) {
37
if (endTime.size() > 0 && endTime.peek() < list.get(i).start) {
38
res.add(new Interval(endTime.peek(), list.get(i).start));
39
}
40
endTime.add(list.get(i).end);
41
}
42
return res;
43
}
44
}
Copied!

3. Time & Space Complexity

Heap: 时间复杂度O(nlogn), n为所有employee的工作时间段,空间复杂度O(n)