Description
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 necessary).
Example
Insert (2, 5)
into [(1,2), (5,9)]
, we get [(1,9)].
Insert (3, 4)
into [(1,2), (5,9)]
, we get [(1,2), (3,4), (5,9)]
.
Test instructions: Given an interval, it is inserted into an orderly set of intervals, and the new interval remains orderly. This takes into account the merging of the intervals, and we can define a new set to hold the final result. Defines a temp cursor that, in turn, takes a loop from the old set to the interval to be compared with the interval to be inserted. So how do you compare it? Assuming that the end of the new zone is less than the start of temp, it means that the range is smaller than temp, so the new interval is placed directly into the result set, and the rest is inserted in turn. Otherwise, a merge of intervals is required, with the following code:
/*** Definition of Interval: * Public classs Interval {* int start, END; * Interval (int start, int end) {* This.start = start; * This.end = end; * } * } */ Public classSolution {/** * @paramintervals:sorted interval list. * @paramnewinterval:new interval. * @return: A new interval list. */ Publiclist<interval> Insert (list<interval>intervals, Interval newinterval) { //Write your code here//discussion of Special situationslist<interval>ans=NewArraylist<interval>(); if(Intervals.size () ==0) {ans.add (newinterval); returnans; } if(newinterval==NULL){ returnintervals; } if(Newinterval.start>intervals.get (Intervals.size ()-1). End) {Intervals.add (newinterval); returnintervals; } //discussion of the general situationInterval last=NULL; for(intI=0;i<intervals.size (); i++){ //I can't use the Newineval .Interval temp=Intervals.get (i); if(newinterval.start>temp.end) {Ans.add (temp); Continue; }Else{ //In two different cases if(newinterval.end<Temp.start) {Ans.add (newinterval); Last=temp; }Else{ intStart=newinterval.start<temp.start?NewInterval.start:temp.start; intEnd=newinterval.end<temp.end?Temp.end:newInterval.end; //Merginglast=NewInterval (start,end); } //to handle the rest. for(intJ=i+1;j<intervals.size (); j + +) {Interval T=Intervals.get (j); if(last.end<T.start) { //Merge CompleteAns.add (last); Last=T; }Else{ //continue to mergeLast.end=last.end>t.end?Last.end:t.end; }} ans.add (last); Break; } } returnans; }}
Insert Interval "Lintcode by Java"