57. Insert Interval
Last updated
Was this helpful?
Last updated
Was this helpful?
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:
Example 2:
Thoughts:
Find the first and last interval index to merge(i,j) and merge them by creating a new interval with (min(firstInterval.start, newInterval.start), max(lastInterval.end, newInterva.end), and adding other intervals that is not merged.
To find the first interval: incre i until intervals[i].end > newInterval.start
To find the last interval: incre j until intervals[j].start > newInterval.end
if i == j == 0; then only need to add _newinterval _in front
if i == j == len, then only need to append _newinterval _in the end
One - Pass: Collect the intervals strictly left or right of the new interval, then merge the new one with the middle ones (if any) before inserting it between left and right ones. 's
Code
Code: Python One pass