Topic
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 is because, the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
Resolution
Test instructions: Give some intervals that have been ordered by the start time, now insert an interval inside, and if there is overlap, merge the intervals, returning the inserted interval sequence.
Idea: Insert first, merge overlapping intervals. Since it is already lined up, you can use the binary search method to place the interval to be inserted. The method of merging overlapping intervals is the same as the "leetcode" merge intervals Problem solving report.
"Java Code"
/** * Definition for an interval. * public class Interval {* int start; * int end; * Interval () {start = 0; end = 0;} * Interval (int s, I NT e) {start = s; end = e;} *} */public class Solution {public list<interval> insert (list<interval> int Ervals, Interval newinterval) {list<interval> ans = new arraylist<interval> (); Insert NewInterval by binary searching int l = 0; int r = intervals.size ()-1; while (L <= r) {int mid = (L + r) >> 1; if (Intervals.get (mid). Start > Newinterval.start) {r = mid-1; } else {L = mid + 1; }} intervals.add (L, NewInterval); Merge all overlapping intervals int start = intervals.get (0). Start; int end = Intervals.get (0). end; for (int i = 1; i < intervals.size (); i++) {Interval inter = intervals.get (i); if (Inter.start > End) {ans.add (new Interval (Start, end)); start = Inter.start; end = Inter.end; } else {end = Math.max (end, inter.end); }} ans.add (new Interval (Start, end)); return ans; }}
"Leetcode" Insert Interval Problem Solving report