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]
.
思路1:
可以分为两种情况。第一种情况,待插入的区间和已有的区间没有重合。第二种情况,待插入的区间和已有的区间重合。对于两种情况,我们都要找到待插区间的位置的范围。下面的代码中,用startItvlIdx和endItvlIdx来表示待插的范围。
/** * 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 startItvlIdx = 0; int endItvlIdx = intervals.size()-1; int i; for(i=0; i<intervals.size(); i++) { if(newInterval.start <= intervals[i].end) { startItvlIdx = i; break; } } if(i==intervals.size()) startItvlIdx = i; for(i=intervals.size()-1; i>-1; i--) { if(newInterval.end >= intervals[i].start) { endItvlIdx = i; break; } } if(i==-1) endItvlIdx = i; if(endItvlIdx<startItvlIdx) // no overlapping between newInterval and intervals { intervals.insert(intervals.begin()+startItvlIdx, newInterval); return intervals; } // there is overlapping between newInterval and intervals Interval mergedItvl; mergedItvl.start = min( newInterval.start, intervals[startItvlIdx].start ); mergedItvl.end = max( newInterval.end, intervals[endItvlIdx].end ); intervals.erase(intervals.begin()+startItvlIdx, intervals.begin()+endItvlIdx+1); intervals.insert(intervals.begin()+startItvlIdx, mergedItvl); return intervals; } };