We are given a list schedule
of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping Intervals
, 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.
(Even though we are representing Intervals
in the form [x, y]
, the objects inside are Intervals
, not lists or arrays. For example, schedule[0][0].start = 1
, schedule[0][0].end = 2
, and schedule[0][0][0]
is not defined). Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.
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.
思路1:sort interval,然后每次判断last.end和next.start的距离,如果不相交,加入间隔进result,否则把last踢掉;
这里用priorityqueue来sort,用collections sort都可以;
/*
// Definition for an Interval.
class Interval {
public int start;
public int end;
public Interval() {}
public Interval(int _start, int _end) {
start = _start;
end = _end;
}
};
*/
class Solution {
public List<Interval> employeeFreeTime(List<List<Interval>> schedule) {
List<Interval> list = new ArrayList<Interval>();
for(List<Interval> intervals: schedule) {
for(Interval interval: intervals) {
list.add(interval);
}
}
Collections.sort(list, (a, b) ->(a.start - b.start));
Interval last = list.get(0);
List<Interval> result = new ArrayList<Interval>();
for(int i = 1; i < list.size(); i++) {
Interval cur = list.get(i);
if(last.end < cur.start) {
result.add(new Interval(last.end, cur.start));
last = cur;
} else {
// last.end >= cur.start;
last.end = Math.max(last.end, cur.end);
}
}
return result;
}
}
思路2:sweep line,起点+1终点-1,count为0的时候,先find 起点,再find终点;NlogN
/*
// Definition for an Interval.
class Interval {
public int start;
public int end;
public Interval() {}
public Interval(int _start, int _end) {
start = _start;
end = _end;
}
};
*/
class Solution {
private class Node {
public int time;
public int flag;
public Node(int time, int flag) {
this.time = time;
this.flag = flag;
}
}
public List<Interval> employeeFreeTime(List<List<Interval>> schedule) {
List<Node> list = new ArrayList<Node>();
for(List<Interval> templist : schedule) {
for(Interval interval: templist) {
list.add(new Node(interval.start, 1));
list.add(new Node(interval.end, -1));
}
}
Collections.sort(list, (a, b) -> (a.time != b.time ? a.time - b.time : a.flag - b.flag));
int count = 0;
Integer start = null;
Integer end = null;
List<Interval> result = new ArrayList<Interval>();
for(Node node : list) {
if(node.flag == 1) {
count++;
if(count == 1 && start != null) {
end = node.time;
if(end > start) {
result.add(new Interval(start, end));
}
start = null;
end = null;
}
} else {
// node.flag == -1;
count--;
if(count == 0) {
start = node.time;
}
}
}
return result;
}
}