标签:interval
Insert Interval : https://leetcode.com/problems/insert-interval/
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].
解析:
因为已经有序,我们可以将原有Intervals分为3部分,完全处于newInterval之前的,和newInterval有重叠的,完全处于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) {
int size = intervals.size();
vector<Interval> res;
int i = 0;
int start = newInterval.start, end = newInterval.end;
// 将newInterval之前的全部压入结果
for (; i < size && start > intervals[i].end; i++) {
res.push_back(intervals[i]);
}
if (i == size) {
res.push_back(newInterval);
return res;
// 重叠区域
start = min(start, intervals[i].start); // 和interval[i]有重叠
for (; i < size && end >= intervals[i].start; i++) {
end = max(end, intervals[i].end); // 所有重叠,直到end < intervals[i].start
}
res.push_back(Interval(start, end)); // 将新Interval入结果。(交叠后的newInterval)
// 剩下的
res.insert(res.end(), intervals.begin()+i, intervals.end());
return res;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:interval
原文地址:http://blog.csdn.net/quzhongxin/article/details/47059709