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]
.
/*** 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) { //traverse intervals, and compare with NewInterval://1 if smaller than NewInterval: add a new result set directly//2 If there is a overlap, dynamically change the newinterval to a new interval, continue merging//3 if larger than NewInterval: add NewInterval to the new collection and then update the NewInterval to the current object//problem-solving ideas: drawing, the first to exclude two non-overlapping cases, the final treatment of overlap,//Notice the change in the median temp, as well as the last temp that needs to be addedList<interval> res=NewArraylist<interval>(); Interval Temp=NewInterval; for(intI=0;i<intervals.size (); i++) {Interval cur=Intervals.get (i); if(cur.start>temp.end) {Res.add (temp); Temp=cur; }Else{ if(temp.start>cur.end) {res.add (cur); }Else{ intstart=math.min (Cur.start,temp.start); intEnd=Math.max (cur.end,temp.end); Interval Newint=NewInterval (start,end); Temp=Newint; }}} res.add (temp); returnRes; }}
[Leedcode 56] Insert Interval