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].
Solution: For example 2:
1. compare [1,2] with [4,9], then insert [1,2];
2. merge [3,5] with [4,9], get newInterval = [3,9];
3. merge [6,7] with [3,9], get newInterval = [3,9];
4. merge [8,10] with [3,9], get newInterval = [3,10];
5. compare [12,16] with [3,10], insert newInterval [3,10], then all the remaining intervals...
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> res; 14 bool insert = false; 15 for(vector<Interval>::iterator it = intervals.begin(); it != intervals.end(); it++) { 16 if(insert || it->end < newInterval.start) { 17 res.push_back(*it); 18 } 19 else if(newInterval.end < it->start) { 20 res.push_back(newInterval); 21 res.push_back(*it); 22 insert = true; 23 } 24 else { 25 newInterval.start = min(newInterval.start, it->start); 26 newInterval.end = max(newInterval.end, it->end); 27 } 28 } 29 if(!insert) res.push_back(newInterval); 30 return res; 31 } 32 };