Title:
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 is because, the new interval [4,9] overlaps with [3,5],[6,7],[8,10] .
Test Instructions:
Given a set of intervals that do not overlap each other, insert a new number of intervals into them (merge if necessary).
You can assume that these intervals are initially sorted according to their starting number.
Example 1:
given [1,3],[6,9", Insert and merge [2,5" get [1,5],[6,9"
Example 2:
given[1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9"   get   [1,2],[3,10],[12,16"
This is because the new interval number [4,9" covered [3,5],[6,7],[8,10"
Algorithm Analysis:
* Combined method "Merge intervals"
* New add NewInterval, reorder and then follow the above method for good
AC Code:
<span style= "FONT-SIZE:12PX;" >public class Solution {public list<interval> Insert (list<interval> intervals, Interval newinterval) {Intervals.add (newinterval); if (intervals = = NULL | | intervals.size () <= 1) return intervals; return merge (intervals); public static list<interval> merge (list<interval> intervals) {if (intervals = = NULL | | intervals . Size () <= 1) return intervals; Sort intervals by using self-defined Comparator collections.sort (intervals, new Intervalcomparator ()); arraylist<interval> result = new arraylist<interval> (); Interval prev = intervals.get (0); for (int i = 1; i < intervals.size (); i++) {Interval Curr = Intervals.get (i); if (prev.end >= curr.start) {//merged case Interval merged = new Interval (prev. Start, Math.max (Prev.end, curr.end));prev = merged; } else {result.add (prev); prev = Curr; }} result.add (prev); return result; }}class Intervalcomparator implements comparator<interval>{public int compare (Interval i1, Interval i2) { return i1.start-i2.start; }}</span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Insert Interval