题目:
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)新的区间在当前区间之前,按顺序输出两个区间。
2)新的区间的前半部分在当前区间中,将新的区间的起始位置改成当前区间的起始位置,即合并两区间,继续遍历。
3)新的区间后半部分在当前区间中,输出以新区间起始,当前区间结束的区间。
4)新的区间在当前区间内,输出当前区间,直接忽略新区间别忘记标记flag。
5)新区间包含当前区间,忽略当前区间,继续遍历。
/** * 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(),i,j; vector<Interval> result; int start=newInterval.start,end=newInterval.end; int flag=0; for(i=0;i<len;++i) { if(flag==1) { result.push_back(intervals[i]); continue; } if(end<intervals[i].start) { flag=1; result.push_back(Interval(start,end)); } if(end>=intervals[i].start&&start<=intervals[i].start) { if(end<=intervals[i].end) { result.push_back(Interval(start,intervals[i].end)); flag=1; } } else if(start>=intervals[i].start&&start<=intervals[i].end) { if(end>=intervals[i].end) start=intervals[i].start; else { flag=1; result.push_back(intervals[i]); } } else { result.push_back(intervals[i]); } } if(flag==0) { result.push_back(Interval(start,end)); return result; } return result; } };