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 in as [2,5]
[1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge in as [4,9]
[1,2],[3,10],[12,16]
.
This is because, the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
"Analyze"
1. Use of a similar previous topic
2. Sort the interval according to the start of the interval first
3. Insert again
Algorithm
/*** Definition for a interval. * public class Interval {* int start; * int end; * Interval () {start = 0; end = 0; } * Interval (int s, int e) {start = s; end = e;} }*/ Public classSolution { Publiclist<interval> Insert (list<interval>intervals, Interval newinterval) {List<Interval> res=NewArraylist<interval>(); Intervals.add (NewInterval); Collections.sort (intervals,NewComparator<interval>() { Public intCompare (Interval i1,interval i2) {returni1.start-I2.start; } }); Interval Pre=intervals.get (0); for(intI=1;i<intervals.size (); i++) {Interval cur=Intervals.get (i); if(pre.end>=cur.start) {Interval merge=NewInterval (Pre.start,math.max (pre.end,cur.end)); Pre=merge; }Else{res.add (pre); Pre=cur; }} res.add (pre); returnRes; }}
57-insert Interval