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 [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This was because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
Test instructions: The problem is very similar to the 56 question, but test instructions gives the start of each interval incrementing, so we don't need to sort. The problem requires us to add a range and then merge. This problem increases the complexity of interval judgment on the basis of 56 questions.
Contains the following six cases as shown.
And these six cases can be combined into three ways of solving. Look at the following code:
/** * 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 class solution { PublicList<interval>Insert(list<interval> intervals, Interval newinterval) {///First to determine if newinterval is within the intervals range if(NewInterval = =NULL)returnintervals;intLen = Intervals.size ();if(len = =0) {Intervals.add (newinterval);returnintervals; } list<interval> res=NewArraylist<interval> (); for(Interval interval:intervals) {if(Interval.end<newinterval.start)//newinterval in the middle of the situation{Res.add (interval); }Else if(Interval.start>newinterval.end)//newinterval inserting the front-end case{Res.add (newinterval); Newinterval=interval;//This place is very important, is to find to insert the interval position, specify the new NewInterval, because the intervals in the interval may also have a place to intersect, need fusion. }Else if(interval.start<=newinterval.end| | Interval.end>=newinterval.start)//Four cases with coincident parts{newinterval=NewInterval (Math.min (Interval.start,newinterval.start), Math.max (Interval.end,newinterval.end)); }} res.add (NewInterval);returnRes }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Java] LeetCode57 Insert Interval