We are given a list scheduleof 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 forallemployees, also in sorted order.
Example 1:
Input:
schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
Output:
[[3,4]]
Explanation:
There are a total of three employees, and all common
free time intervals would be [-inf, 1], [3, 4], [10, inf].
We discard any intervals that contain inf as they aren't finite.
(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:
schedule and schedule[i] are lists with lengths in range [1, 50].
0 <= schedule[i].start < schedule[i].end <= 10^8.
Solution & Analysis
类似于Meeting Room问题
/**
* 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; }
* }
*/
class Solution {
public List<Interval> employeeFreeTime(List<List<Interval>> avails) {
List<Interval> result = new ArrayList<>();
List<Interval> timeLine = new ArrayList<>();
avails.forEach(e -> timeLine.addAll(e));
Collections.sort(timeLine, ((a, b) -> a.start - b.start));
Interval temp = timeLine.get(0);
for (Interval each : timeLine) {
if (temp.end < each.start) {
result.add(new Interval(temp.end, each.start));
temp = each;
} else {
temp = temp.end < each.end ? each : temp;
}
}
return result;
}
}