Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]output: [[1,6],[8,10],[15,18]]explanation:since intervals [1,3] and [2,6] overlaps , merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]output: [[1,5]]explanation:intervals] [1,4] and [4,5] are considerred overlapping.
The example of this problem is observed if the interval is based on the minimum order of the word will be better to do, or find to find the complexity should be very high bar, the order of the most is O (nlogn). After sorting it is better to think, if the beginning of the next interval is smaller than the last interval, it proves that there is coverage, then need to merge the interval. The merge also takes a look at the end of the front and back intervals, taking the larger one as the end of the merge. If the beginning of the latter interval does not cover the end of the previous interval, it is a new interval. Save the previous interval in the results and continue looking for a new interval.
Java
/*** 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;} }*/classSolution { PublicList<interval> Merge (list<interval>intervals) { intLen =intervals.size (); if(Len <= 1)returnintervals; Collections.sort (intervals,NewCMP ()); List<Interval> res =NewArraylist<interval>(); intStart = Intervals.get (0). Start, end = Intervals.get (0). End; for(inti = 1; i < Len; i++) { if(Intervals.get (i). Start <=end) {End= end > Intervals.get (i). End?End:intervals.get (i). end; } Else{Res.add (NewInterval (start, end)); Start=Intervals.get (i). Start; End=Intervals.get (i). end; }} res.add (NewInterval (start, end)); returnRes; } classCmpImplementsComparator<interval> { Public intCompare (Interval i1, Interval i2) {returnI1.start-I2.start; } }}
(Java) Leetcode 56. Merge intervalse--merging interval