首页 > 代码库 > 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].

 

向已经有序的且没重合的区间集合中插入新区间,并合并由此引来的重合区间,输出。

 1 /** 2  * Definition for an interval. 3  * struct Interval { 4  *     int start; 5  *     int end; 6  *     Interval() : start(0), end(0) {} 7  *     Interval(int s, int e) : start(s), end(e) {} 8  * }; 9  */10 class Solution {11 public:12     vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {13         vector<Interval> ans;   //存放结果14         int i=0;15         while( i<intervals.size() && intervals[i].end < newInterval.start ) //如果旧区间的end小于新区间的start,那么直接放入结果中16             ans.push_back( intervals[i++] );17         if( i == intervals.size() ) {   //处理特定的情况,及新区间的start比旧区间最后一个区间的end还大18             ans.push_back(newInterval);19             return ans;20         }21         //不断合并重复区间,直到第一个旧区间的start大于新区间的end22         while( i<intervals.size() && intervals[i].start <= newInterval.end ) {23             newInterval.start = min(intervals[i].start, newInterval.start);24             newInterval.end = max(intervals[i].end, newInterval.end);25             ++i;26         }27         ans.push_back(newInterval);28         while( i<intervals.size() ) ans.push_back(intervals[i++]);  //将后面不需要合并的区间放入结果中29         return ans;30     }31 };

 

Insert Interval