题目
地址: https://leetcode.com/problems/insert-interval/description/
类别: Sort
难度: Hard
描述:
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].
分析
给定一组有序且互不相交的区间,现在需要插入一个新区间,且若新区间与原来这些区间有重合部分就将相应部分合并得到新的区间。
例:
Input:
[1,3],[6,9]
[2,5]
新区间[2,5]与[1,3]有部分重合,因此合并得到新区间[1,5],并将相关原区间删去,最后:
Output: [1,5],[6,9]
思路
整个问题的关键在于找到与合并相关的区间,将它们与新区间合并再加上其他区间即可得到最后的结果。不难发现若存在多个需合并区间,那么它们一定是连续的,因此我们只需要找到起始合并区间与终点合并区间即可。
至于起终点的确定,我们可以通过比较新区间与其他区间的start与end值确定:
1. 确定起点区间:
while(i < intervals.size() && intervals[i].end < newInterval.start) i++;
2. 确定终点区间:
while(i < intervals.size() && newInterval.end >= intervals[i].start) i++;
然后将这些区间与新区间合并,再加上其它无关区间。
代码:
/**
* 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) {
int start = newInterval.start, end = newInterval.end;
//decide start position of merge section
int i = 0;
while(i < intervals.size() && intervals[i].end < newInterval.start) i++;
if(i != intervals.size()) start = min(intervals[i].start, newInterval.start);
while(i < intervals.size() && newInterval.end >= intervals[i].start) {
end = max(intervals[i].end, newInterval.end);
intervals.erase(intervals.begin()+i);
}
Interval mergeInterval(start, end);
intervals.insert(intervals.begin()+i, mergeInterval);
return intervals;
}
};
上面的代码实现利用原来的数组存储最后结果,空间复杂度较小,但因为涉及到删除操作,所以时间复杂度比较大。下面的是降低时间复杂度但花费了空间的方法:
/**
* 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;
int start = newInterval.start, end = newInterval.end;
int i = 0;
while(i < intervals.size() && intervals[i].end < newInterval.start) {
result.push_back(intervals[i]);
i++;
}
if(i != intervals.size()) start = min(intervals[i].start, newInterval.start);
while(i < intervals.size() && newInterval.end >= intervals[i].start) i++;
if(i-1 != intervals.size() && i-1 != -1) end = max(intervals[i-1].end, newInterval.end);
Interval mergeInterval(start, end);
result.push_back(mergeInterval);
while(i < intervals.size()) {
result.push_back(intervals[i]);
i++;
}
return result;
}
};