扫描线
注意是 vector[HTML_REMOVED]>& schedule, 所以我们先要二维转一维。
all.insert(all.end(), intervals.begin(), intervals.end());
其次最后要用 res.emplace_back(prevEnd, start);
emplace_back 是 C++11 引入的函数,它允许我们在向量的末尾直接构造新元素,而无需显式创建一个临时对象。通过 emplace_back,我们可以在向量的末尾直接构造 Interval 对象,并避免了额外的拷贝或移动操作。
与之相比,push_back 函数需要接受一个已经构造好的对象作为参数,并将其拷贝(或移动)到向量的末尾。在这种情况下,使用 emplace_back 可以更高效地构造对象,因为我们可以直接在向量的内存空间中构造对象,而不需要进行额外的拷贝或移动操作。
综上所述,使用 emplace_back 可以在向量的末尾直接构造对象,避免了额外的拷贝或移动操作,从而提高了代码的效率。
代码
/*
// Definition for an Interval.
class Interval {
public:
int start;
int end;
Interval() {}
Interval(int _start, int _end) {
start = _start;
end = _end;
}
};
*/
class Solution {
public:
vector<Interval> employeeFreeTime(vector<vector<Interval>>& schedule) {
vector<Interval> all;
for (const auto intervals : schedule) {
all.insert(all.end(), intervals.begin(), intervals.end());
}
sort(all.begin(), all.end(), [](const Interval& a, const Interval& b){
return a.start < b.start;
});
vector<Interval> res;
int prevEnd = all[0].end;
for (const auto& [start, end] : all) {
if (start > prevEnd)
res.emplace_back(prevEnd, start);
prevEnd = max(prevEnd, end);
}
return res;
}
};