Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
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 was because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
The requirement for this problem is to give a set of non-overlapping, start-time intervals in which a new interval is inserted.
Of course, this problem can be done with the code inside the merge intervals, first add the new interval to the array, and then merge. The complexity of Time is O (Nlogn).
In fact, you can also not sort, directly insert the time interval, the location of the insertion interval can be divided into three parts:
- To the left of the insertion position
- Insertion position (overlapping or no overlap)
- To the right of the insertion position
These three sections are processed separately and can only be handled when the insertion position is processed.
Time complexity: O (N)
Space complexity: O (N)
1 class Solution2 {3 Public:4 Vector<Interval> Insert(Vector<Interval> &intervals, Interval NewInterval)5 {6 Vector<Interval> VI;7 8 int I = 0;9 while(I < intervals.size() && intervals[I].End < NewInterval.Start)Ten VI.push_back(intervals[I ++]); One A VI.push_back(NewInterval); - while(I < intervals.size() && VI[VI.size() - 1].End >= intervals[I].Start) - { the VI[VI.size() - 1].Start = min(intervals[I].Start, VI[VI.size() - 1].Start); - VI[VI.size() - 1].End = Max(intervals[I].End, VI[VI.size() - 1].End); - ++ I; - } + - while(I < intervals.size()) + VI.push_back(intervals[I ++]); A at return VI; - } - };
Reprint please indicate source: Leetcode---57. Insert Interval
Leetcode---57. Insert Interval