1.题目描述
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.
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.
Example 2:
Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
Output: [[5,6],[7,9]]
(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.
2. 代码
分析:将所有的区间放到一起,按开始时间从小到大排序(如果开始时间相同则根据结束时间的先后,思考为什么?),这样处理后,进行一次遍历.
如果两个区间之间没有空闲时间而存在交集,那么将这两个交集合二为一(取两者的最小开始时间和最大结束时间)
如果存在空闲区间,那么将该区间放入结果中!
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> employeeFreeTime(vector<vector<Interval>>& schedule) {
vector<Interval> all;
for(vector<Interval> tmp : schedule) {
for(Interval s : tmp) {
all.push_back(s);
}
}
sort(all.begin(), all.end(), comp);
for(int i = 0; i<all.size(); ++i)
cout << "[" << all[i].start << "," << all[i].end << "]" << endl;
vector<Interval> res;
for(int i = 0; i < all.size()-1; ++i) {
if(all[i].end < all[i+1].start) {
cout << all[i].end << ", " << all[i+1].start << endl;
Interval interval(all[i].end, all[i+1].start);
res.push_back(interval);
} else {
all[i+1].start = min(all[i].start, all[i+1].start);
all[i+1].end = max(all[i].end, all[i+1].end);
}
}
return res;
}
static bool comp(const Interval& s1, const Interval& s2) {
if(s1.start < s2.start) return true;
else if(s1.start == s2.start) {
if(s1.end <= s2.end) return true;
else return false;
}
else return false;
}
};
联系邮箱:sysuygm@163.com
本文介绍了一种算法,用于计算一组员工的共同空闲时间段。输入为每个员工的工作时间区间列表,输出为所有员工共同的正长度空闲时间区间列表。通过合并所有员工的时间区间并排序,再遍历这些区间来确定空闲时间。
1353

被折叠的 条评论
为什么被折叠?



