题目:
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]
. (Hard)
分析:
首先可以采用merge interval的方法,先把区间填进去,然后排序,最后再调用merge,复杂度O(NlogN)
代码:
/**
* 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 {
private:
static bool cmp (const Interval& I1, const Interval& I2) {
return I1.start < I2.start;
}
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> result;
if (intervals.size() == ) {
return result;
}
sort(intervals.begin(), intervals.end(), cmp);
int left = intervals[].start, right = intervals[].end;
for (int i = ; i < intervals.size(); ++i) {
if (intervals[i].start <= right) {
right = max(right,intervals[i].end);
}
else {
result.push_back(Interval(left,right));
left = intervals[i].start;
right = intervals[i].end;
}
}
result.push_back(Interval(left,right));
return result;
}
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> result;
intervals.push_back(newInterval);
sort(intervals.begin(),intervals.end(),cmp);
result = merge(intervals);
return result;
}
};
当然还有O(N)的算法可以优化。
分三步来做:
第一步,找到左侧不跟newInterval相交的区间添加到结果中;
第二步,找到所有和newInterval相交的区间并找到其左边界和右边界,然后建立新的interval添加到结果中;
第三部,找到右侧不跟newInterval相交的区间添加到结果中。
注意很多细节在里面可能会犯错
代码:
/**
* 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) {
vector<Interval> result;
if (intervals.size() == ) {
result.push_back(newInterval);
return result;
}
int i = ;
while (i < intervals.size() && intervals[i].end < newInterval.start) {
result.push_back(intervals[i++]);
}
int left = ;
if (i == intervals.size()) {
left = newInterval.start;
}
else {
left = min(newInterval.start,intervals[i].start);
}
while (i < intervals.size() && intervals[i].start <= newInterval.end) {
i++;
}
int right = ;
if (i >= ) {
right = max(newInterval.end, intervals[i - ].end);
}
else {
right = newInterval.end;
}
result.push_back(Interval(left,right));
while (i < intervals.size() ) {
result.push_back(intervals[i++]);
}
return result;
}
};