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]
.
思路:插入区间数,关键就是找到位置,如果出现覆盖的地方,则合并;如果没有覆盖的地方,则找到位置后插入。
1)搜索newInterval.start大于左边的区间数,则将这些区间数放入result中;
2)搜索newInterval.end小于右边的区间数时,则将newInterval放入result中;同时将右边的区间数依次放入reuslt中;
3)覆盖的地方,则要判断newInterva和intervals[i]那个start最小,哪个end最大的情况;
最后判断循环遍历结束没有查找到newInterval的位置或者result为空的情况,故将newInterval push到result中。
/** * 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 len=intervals.size(); vector<Interval> result; result.clear(); for(int i=0;i<len;i++) { //处理newInterval左边的区间数 if(intervals[i].end<newInterval.start) { result.push_back(intervals[i]); } //处理newInterval右边的区间数 else if(intervals[i].start>newInterval.end) { result.push_back(newInterval); while(i<len) { result.push_back(intervals[i]); i++; } } //处理newInterval覆盖的地方 else { newInterval.start=min(newInterval.start,intervals[i].start); newInterval.end=max(newInterval.end,intervals[i].end); } } if(result.size()==0||result.back().end<newInterval.start) result.push_back(newInterval); return result; } };
网上一大神贴出了O(logN),二分查找来完成这道题——Insert interval.