首页 > 代码库 > Insert Interval
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]
.
思路:
分3种情况讨论:
首先,如果插入的元素的start一直大于上一个的结束end,那么说明还没找到要插入的位置;
如果找到要插入的位置,即有start小于end。如果要插入的元素的end也小于找到要插入点的start,说明没有交集,直接将元素插入,设置标志位用来控制该新插入的元素只插入一次。
否则,如果插入的元素与后一个区间有交集,则将新插入的元素与后一个区间合并成新的要插入的元素,继续重复上面的过程。记得要判断flag看要插入的元素是否插入了。
C++实现代码:
#include<iostream>#include<vector>#include<algorithm>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<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval> 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[i].start) { if(flag==1) ret.push_back(intervals[i]); else { flag=1; ret.push_back(newInterval); ret.push_back(intervals[i]); } } else { newInterval.start=min(newInterval.start,intervals[i].start); newInterval.end=max(newInterval.end,intervals[i].end); } } if(flag==0) ret.push_back(newInterval); return ret; }};int main(){ Solution s; Interval a1(1,2); Interval a2(3,5); Interval a3(6,7); Interval a4(8,10); Interval a5(12,16); vector<Interval> intervals= {a1,a2,a3,a4,a5}; Interval newInternal= {0,0}; vector<Interval> result=s.insert(intervals,newInternal); for(auto a:result) cout<<"[ "<<a.start<<" , "<<a.end<<" ]"<<endl;}
运行结果:
Insert Interval
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。