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]
.
思路:
分3种情况讨论:
首先,如果插入的元素的start一直大于上一个的结束end,那么说明还没找到要插入的位置;
如果找到要插入的位置,即有start小于end。如果要插入的元素的end也小于找到要插入点的start,说明没有交集,直接将元素插入,设置标志位用来控制该新插入的元素只插入一次。
否则,如果插入的元素与后一个区间有交集,则将新插入的元素与后一个区间合并成新的要插入的元素,继续重复上面的过程。记得要判断flag看要插入的元素是否插入了。
C++实现代码:
#include#include #include using namespace std;struct Interval{ int start; int end; Interval():start(0),end(0) {} Interval(int s,int e):start(s),end(e) {}};class Solution{public: vector insert(vector &intervals, Interval newInterval) { vector ret; if(intervals.empty()) { ret.push_back(newInterval); return ret; } int flag=0; int i; for(i=0; i<(int)intervals.size(); i++) { if(newInterval.start>intervals[i].end) { ret.push_back(intervals[i]); } else if(newInterval.end intervals= {a1,a2,a3,a4,a5}; Interval newInternal= { 0,0}; vector result=s.insert(intervals,newInternal); for(auto a:result) cout<<"[ "< <<" , "< <<" ]"<
运行结果:
class Solution {public: vectorinsert(vector &intervals, Interval newInterval) { if(intervals.empty()) return vector ({newInterval}); vector res; int i; int flag=false; for(i=0; i