题目:
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].
题意:
给定一些区间,这些区间不重合,并且按照区间的前面的值已经进行了排序。
现在给你一个区间,将这个区间插入到这个区间中,进行适当合并,不要有重合的区间。
思路:
这道题目采用http://blog.csdn.net/u014673347/article/details/48024753题的思路。我们可以先将元素插入到指定的位置,通过upper_bound找出大于这个区间前端的第一个元素,然后将这个新的区间插入到这个元素前面。接下来要做的事情就是将这个新插入的区间与相邻区间进行合并,如果前面区间能够与这个新插入的区间合并,那么进行合并,否则,让这个区间的后面的区间尝试与之合并,找不到合并的时候就是合并完成的时候。
以上。
代码如下:
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
struct myCompare {
bool operator()(const Interval& a, const Interval& b) {
return (a.start < b.start);
}
}mycompare;
class Solution {
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
int size = intervals.size();
if (size == 0) {
vector<Interval> res;
res.push_back(newInterval);
return res;
}
auto insert_position = upper_bound(intervals.begin(), intervals.end(), newInterval, mycompare);//找到该插入的位置
auto position = intervals.insert(insert_position, newInterval);//插入新的区间
vector<Interval> result;
int first = (position - intervals.begin() - 1), second = first + 1;
if (first == -1){//这个新插入的元素可能插到了最前端
first = 0;
second = 1;
}
result.insert(result.end(),intervals.begin(), intervals.begin() + first);//将从begin到first-1的那些区间插入到结果值中。
if (intervals[second].start > intervals[first].end) {
result.push_back(intervals[first]);//first是插入的区间的前面的一个区间,由于新的区间与这个之前的区间不能合并,那么将前面的区间放入结果中。
first++;
second++;
}
size++;//因为新插入了一个元素,所以元素增加了一个
while (second < size) {
if (intervals[second].start <= intervals[first].end) {
intervals[first].end = max(intervals[first].end, intervals[second].end);
second++;
}
else break;
}
result.push_back(intervals[first]);
if (second != size)result.insert(result.end(), intervals.begin() + second, intervals.end());
return result;
}
};