Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] inas [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlapswith [3,5],[6,7],[8,10].
思路:本题与《Merge Intervals》类似,可以沿用其中的思路:首先将new interval插入到interval数组中,排序,然后重新merge即可。
但是本题因为有这样的预设:”the intervals were initially sorted according to their start times.”。intervals数组已经是按照start排好序的了,所以,可以按照《Merge Intervals》思路,一次遍历即可解决问题:在merge遍历原数组时,找到new interval合适的插入位置,加入到merge过程中。
但是这种算法需要考虑的边界条件有点多,思路上也不如《Merge Intervals》清晰。下面的代码就是这种思路的实现:
struct Interval* insert(struct Interval* intervals, int intervalsSize, struct Interval newInterval, int* returnSize)
{
struct Interval *res = NULL;
int reslen = 0;
int laststart, lastend;
struct Interval *curnode = NULL;
int i = 0, j = 0;
int flag = 0;
if(intervalsSize == 0)
{
res = calloc(1, sizeof(struct Interval));
res->start = newInterval.start;
res->end = newInterval.end;
*returnSize = 1;
return res;
}
//新插入节点与第一个元素的start进行比较
if(newInterval.start < intervals[0].start)
{
laststart = newInterval.start;
lastend = newInterval.end;
j = 0;
}
else
{
laststart = intervals[0].start;
lastend = intervals[0].end;
j = 1;
}
for(i = j; i < intervalsSize; i++)
{
if(newInterval.start > intervals[i].start || flag)
{
curnode = intervals+i;
}
else
{
curnode = &newInterval;
flag = 1;
i--;
}
if(curnode->start <= lastend)
{
if(curnode->end > lastend)
{
lastend = curnode->end;
}
}
else
{
reslen++;
res = realloc(res, reslen*sizeof(struct Interval));
res[reslen-1].start = laststart;
res[reslen-1].end = lastend;
laststart = curnode->start;
lastend = curnode->end;
}
}
//新插入节点的start比数组中所有元素的start都要大
if(flag == 0)
{
if(newInterval.start <= lastend)
{
if(newInterval.end > lastend)
{
lastend = newInterval.end;
}
}
else
{
reslen++;
res = realloc(res, reslen*sizeof(struct Interval));
res[reslen-1].start = laststart;
res[reslen-1].end = lastend;
laststart = newInterval.start;
lastend = newInterval.end;
}
}
reslen++;
res = realloc(res, reslen*sizeof(struct Interval));
res[reslen-1].start = laststart;
res[reslen-1].end = lastend;
*returnSize = reslen;
return res;
}