/**
* 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> insert(vector<Interval> &intervals, Interval newInterval) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (intervals.size() == 0)
{
intervals.push_back(newInterval);
return intervals;
}
vector<Interval>::iterator iterBeg = intervals.end();
vector<Interval>::iterator iterEnd = intervals.end();
vector<Interval>::iterator iter;
bool isFound = false;
for (iter = intervals.begin(); iter != intervals.end(); ++iter)
{
if (!isFound) //搜索第一个重叠的区间或者完全在其右侧的区间
{
if (isOverlapping(newInterval, *iter)) //找到第一个重叠的区间
{
iterBeg = iter;
isFound = true;
}
else if (isLeft(newInterval, *iter)) //找到第一个在其右侧的区间
{
iterEnd = iter;
break;
}
}
else
{
if (!isOverlapping(newInterval, *iter)) //找到最后一个重叠的区间的下一个
{
iterEnd = iter;
break;
}
}
}
if (!isFound) //无重叠情况,直接插入
{
intervals.insert(iterEnd, newInterval);
}
else //有重叠情况,先合并区间,再删去原数组中与新区间重叠的区间,再插入
{
Interval mergeInterval;
mergeInterval.start = min(newInterval.start, iterBeg->start);
mergeInterval.end = max(newInterval.end, (iterEnd - 1)->end);
iterEnd = intervals.erase(iterBeg, iterEnd);
intervals.insert(iterEnd, mergeInterval);
}
return intervals;
}
bool isOverlapping(const Interval &i1, const Interval &i2)
{
return i1.end >= i2.start && i1.start <= i2.end;
}
bool isLeft(const Interval &i1, const Interval &i2)
{
return i1.end < i2.start;
}
};