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]
.
class Solution { public: vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { if (intervals.empty()) { intervals.push_back(newInterval); return intervals; } if (newInterval.end < intervals[0].start) { intervals.insert(intervals.begin(), newInterval); return intervals; } if (newInterval.end == intervals[0].start) { intervals[0].start= newInterval.start; return intervals; } int k = 0; while (k <intervals.size()) { while (k <intervals.size() && intervals[k].end < newInterval.start) k++; if (k == intervals.size()) { intervals.push_back(newInterval); return intervals; } if (intervals[k].start > newInterval.end) { intervals.insert(intervals.begin() + k, newInterval); return intervals; } intervals[k].start = newInterval.start < intervals[k].start ? newInterval.start: intervals[k].start; if (intervals[k].end >= newInterval.end) return intervals; int end = newInterval.end; int kk = k; while (kk < intervals.size() && end >= intervals[kk].end) kk++; if (kk == intervals.size()) { intervals[k].end = end; intervals.erase(intervals.begin() + k + 1, intervals.end()); return intervals; } if (intervals[kk].start <= end) { intervals[k].end = intervals[kk].end; intervals.erase(intervals.begin() + k + 1, intervals.begin() + kk+1); return intervals; } intervals[k].end = end; intervals.erase(intervals.begin() + k + 1, intervals.begin() + kk); return intervals; } } };