先上题干,leetcode的原题:
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]
in as [1,2],[3,10],[12,16]
.
This is because the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
跟Merge Intervals挺像的,就是在已经合并好的间隙中插入一个新的间隙并合并。
-,-已经做出了Merge Intervals可以直接用之前的代码,只要插入一个interval再排个序就是一样的了。。。
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval)
{
intervals.push_back(newInterval);
sort(intervals.begin(), intervals.end());
vector<Interval>res;
for (int i = 0; i < intervals.size();)
{
res.push_back(intervals[i]);
for (i++; i < intervals.size() && intervals[i].start <= res.back().end; i++)
res.back().end = max(intervals[i].end, res.back().end);
}
return res;
}
这个代码看起来很简洁,也好理解,找出相邻可以合并的Interval的最大end,就合并。
但很明显效率很低,因为只有新插入的interval需要处理。leetcode上跑了34ms,十分落后。于是重新写了一个,原理本应该很简单的,找到newInterval的start的位置,然后找到newInterval的end的位置,合并就好了。
但是中间的各种判断弄的很纠结,如果不是leetcode上会显示错的例子,还不知道要纠结多久……逻辑还是不够缜密啊。
vector<Interval> insert2(vector<Interval> &intervals, Interval newInterval)
{
vector<Interval>res;
auto i = intervals.begin();
for (; i != intervals.end() && i->end < newInterval.start; i++)
{
if (i->start < newInterval.start)
res.push_back(*i);
}
if (i != intervals.end())
newInterval.start = min(i->start, newInterval.start);
for (; i != intervals.end() && i->end <= newInterval.end; i++);
if (i != intervals.end() && newInterval.end >= i->start)
{
newInterval.end = i->end;
i++;
}
res.push_back(newInterval);
for (; i != intervals.end(); i++)
res.push_back(*i);
return res;
}
这个效率还不错,19ms达到了中等偏上一点的水平吧。