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].
思路:和上一题差不多,但要考虑更多问题,注意不要漏掉newInterval可能整体插入(不做merge)的情况
/** * 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) { if(intervals.empty()){ intervals.push_back(newInterval); return intervals; } //first find the fist end >= newInterval.start vector<Interval>::iterator startInsertPos = intervals.begin(); for(; startInsertPos < intervals.end(); startInsertPos++){ if(startInsertPos->end >= newInterval.start) break; } if(startInsertPos == intervals.end()){ //insert in the final intervals.push_back(newInterval); return intervals; } //find the last start <= newInterval.end vector<Interval>::iterator endInsertPos = startInsertPos; for(; endInsertPos < intervals.end(); endInsertPos++){ if(endInsertPos->start > newInterval.end){ break; } } endInsertPos--; //intervals between [startInsertPos, endInsertPos] may need to be merged //case 1: insert before startInsertPos if(startInsertPos->start > newInterval.end){ intervals.insert(startInsertPos,newInterval);//insert in the position startInserPos } //case2: insert after endInsertPos else if(endInsertPos->end < newInterval.start){ intervals.insert(endInsertPos+1,newInterval);//insert in the position endInsertPos+1 } //case3: merge else{ startInsertPos->start = min(newInterval.start, startInsertPos->start); startInsertPos->end = max(newInterval.end, endInsertPos->end); intervals.erase(startInsertPos+1,endInsertPos+1);//erase the elem from startInserPos+1 to endInsertPos } return intervals;