对于一个排序的non-overlap的Interval集合。插入一个Interval。
遍历插入的情况。思路比较简单,代码如下:
/**
* 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:
bool is_overlap(const Interval& rhs,const Interval& rhl){
if (rhs.start<=rhl.end && rhs.start>=rhl.start)return true;
if (rhl.start<=rhs.end && rhl.start>=rhs.start)return true;
return false;
}
Interval mergeTwo(const Interval& inter, Interval& newInterval){
if (inter.start>=newInterval.start && inter.start<=newInterval.end){
Interval res;
res.start = newInterval.start;
res.end = newInterval.end>inter.end? newInterval.end:inter.end;
return res;
}
if (inter.start<=newInterval.start && inter.end>=newInterval.start){
Interval res;
res.start = inter.start;
res.end = newInterval.end>inter.end? newInterval.end:inter.end;
return res;
}
}
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> res;
for (const auto& inter:intervals){
if (is_overlap(inter,newInterval)){
/*
*/
newInterval = mergeTwo(inter,newInterval);
}else{
res.push_back(inter);
}
}
res.push_back(newInterval);
sort(res.begin(),res.end(),[](const auto& rhs,const auto& rhl){return rhs.end<rhl.end;});
return res;
}
};
网友评论