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]].
This problem remember the first time when the brush took a long time to do out, read the next nine chapters on the algorithm affixed to the answer, I think the answer is written well, as follows
/*** Definition of Interval: * Public classs Interval {* int start, END; * Interval (int start, int end) {* This.start = start; * This.end = end; * } */classSolution {/*** Insert newinterval into intervals. * @paramintervals:sorted interval list. * @paramnewinterval:a new interval. * @return: A new sorted interval list. */ Publicarraylist<interval> Insert (arraylist<interval>intervals, Interval newinterval) {ArrayList<Interval> result =NewArraylist<interval>(); //Write your code here if(Intervals = =NULL|| NewInterval = =NULL) return NULL; intinsertposition = 0; for(Interval interval:intervals) {if(Newinterval.start >interval.end) {Result.add (interval); Insertposition++; } Else if(Newinterval.end <Interval.start) {Result.add (interval); } Else{Newinterval.start=math.min (Newinterval.start, Interval.start); Newinterval.end=Math.max (Newinterval.end, interval.end); }} result.add (Insertposition, newinterval); returnresult; }}
Lintcode-easy-insert Interval