Insert intervals
Given a non-overlapping interval list which is sorted by start point.
Insert a new interval into it, make sure the list was still in order and non-overlapping (merge intervals if neces Sary).
Example
Insert [2, 5] into [[up], [5,9]], we get [[1,9]].
Insert [3, 4] into [[up], [5,9]], we get [[up], [3,4], [5,9]].
Analysis:
Create a new array list, insert the smaller interval in the new array and use a counter to keep track of the total number of smaller intervals. If we find an interval overlapping with the new one, we need to the change the start and end.
1 /**2 * Definition of Interval:3 * Public classs Interval {4 * int start, end;5 * Interval (int start, int end) {6 * This.start = start;7 * this.end = end;8 * }9 */Ten One classSolution { A /** - * Insert newinterval into intervals. - * @param intervals:sorted interval list. the * @param newinterval:a new interval. - * @return: A new sorted interval list. - */ - + Publicarraylist<interval> Insert (arraylist<interval>intervals, Interval newinterval) { - if(NewInterval = =NULL|| intervals = =NULL) { + returnintervals; A } at -arraylist<interval> results =NewArraylist<interval>(); - intInsertpos =0; - - for(Interval interval:intervals) { - if(Interval.end <Newinterval.start) { in Results.add (interval); -insertpos++; to}Else if(Interval.start >newinterval.end) { + Results.add (interval); -}Else { theNewinterval.start =math.min (Interval.start, newinterval.start); *Newinterval.end =Math.max (Interval.end, newinterval.end); $ }Panax Notoginseng } - the Results.add (Insertpos, newinterval); + returnresults; A the } +}
Merge intervals
Given a collection of intervals, merge all overlapping intervals.
Example
Given intervals = merged intervals:
[ [ [1, 3], [1, 6], [2, 6], => [8, 10], [8, 10], [15, 18] [15, 18] ]]
Analyze:
Sort first, then merge intervals if they overlap.
1 /**2 * Definition of Interval:3 * public class Interval {4 * int start, end;5 * Interval (int start, int end) {6 * This.start = start;7 * this.end = end;8 * }9 */Ten One classSolution { A /** - * @param intervals, a collection of intervals - * @return: A new sorted interval list. the */ - PublicList<interval> Merge (list<interval>list) { - - if(List = =NULL|| List.size () <=1) { + returnlist; - } + ACollections.sort (list,NewComparator<interval>(){ at Public intCompare (Interval A, Interval b) { - returnA.start-B.start; - }}); - - for(inti =1; I < list.size (); i++) { - //No intersection in if(overlap (List.Get(i), list.GetI1))) { -List.GetI1). Start = Math.min (list.Get(i). Start, list.GetI1). Start); toList.GetI1). End = Math.max (list.Get(i). end, list.GetI1). end); + List.remove (i); -i--; the } * } $ returnlist;Panax Notoginseng } - the boolean overlap (Interval i1, Interval i2) { + returnMath.max (I1.start, I2.start) <=math.min (I1.end, i2.end); A } the}
Insert Interval & Merge intervals