56. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
return [1,6],[8,10],[15,18]
.
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * int start; 5 * int end; 6 * Interval() { start = 0; end = 0; } 7 * Interval(int s, int e) { start = s; end = e; } 8 * } 9 */ 10 public class Solution { 11 public List<Interval> merge(List<Interval> intervals) { 12 if(intervals.size()<2) return intervals; 13 // sort by ascending start pointer by using annoymous comparator 14 //intervals.sort((i1,i2)->Integer.compare(i1.start,i2.start)); 15 Comparator<Interval> comp = new Comparator<Interval>(){ 16 public int compare(Interval i1,Interval i2){ 17 return i1.start-i2.start; 18 } 19 }; 20 Collections.sort(intervals,comp); 21 int start = intervals.get(0).start; 22 int end = intervals.get(0).end; 23 // store the result Interval list 24 List<Interval> result = new ArrayList<>(); 25 for(Interval interval:intervals){ 26 if(interval.start<=end){ 27 // overlapping intervals,move the end if needed 28 end = Math.max(end,interval.end); 29 }else{ 30 //Disjoint interval, add the previous one and reset the bounds 31 result.add(new Interval(start,end)); 32 start = interval.start; 33 end = interval.end; 34 } 35 } 36 result.add(new Interval(start,end)); 37 return result; 38 } 39 } 40 //as for the run time complexity ,sort time costs nlogn time. compare the intervals and put it into result costs O(n) time ,so the total run time could be nlogn,the space complexity would be O(n);