Merge IntervalA number of closed intervals are given and all overlapping parts are merged.
Sample Example
The given interval list is the combined interval list:
[ [ [1, 3], [1, 6], [2, 6], => [8, 10], [8, 10], [15, 18] [15, 18] ]]
challenges
O (n log n) Time and O (1) extra space.
The idea is clear and the code is confusing. Sort the list by using the Collection.sort () method first. Of course, you can toarray () and then sort by arrays.sort (). But all need to write an inner class that implements the comparator interface.
1 /**2 * Definition of Interval:3 * public class Interval {4 * int start, end;5 * Interval (int start, int end) {6 * This.start = start;7 * this.end = end;8 * }9 */Ten One classSolution { A /** - * @paramintervals:sorted interval list. - * @return: A new sorted interval list. the */ - - Public classintervalcmpImplementsComparator<interval> { - Public intCompare (Interval i1, Interval i2) { + if(I1.start < I2.start)return-1; - if(I1.start = = I2.start && i1.end <= i2.end)return-1; + return1; A } at } - PublicList<interval> Merge (list<interval>intervals) { - if(intervals.size () = = 1)returnintervals; -list<interval> list =NewArraylist<interval>(); - intMax1 =-1; - intMin1 = 99999999; in intmax =-1; - intMin = 99999999; to + //with collections. Sort (), Baidu a bit JDK7 not add this sentence may be error -System.setproperty ("Java.util.Arrays.useLegacyMergeSort", "true"); theCollections.sort (intervals,Newintervalcmp ()); * $ for(inti = 0;i<intervals.size (); i++) {Panax NotoginsengInterval x =Intervals.get (i); - if(X.start > Max1 | | x.end <min1) { theMin =X.start; +Max =X.end; A for(intj = I+1;j<intervals.size (); j + +) { theInterval y =Intervals.get (j); + if(y.end >= min && y.start <=max) { - if(Max <y.end) { $Max =Y.end; $ } - if(Min >Y.start) { -Min =Y.start; the } - }Wuyi } theX.end =Max; -X.start =min; Wu if(Max1 < max) Max1 =Max; - if(Min1 > min) min1 =min; About List.add (x); $ } - } - returnlist; - } A +}
View Code
Merge interval (lintcode)