[Leetcode] 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]
.
Solution:
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 static public class MyCompare implements Comparator<Interval> { 12 @Override 13 public int compare(Interval o1, Interval o2) { 14 // TODO Auto-generated method stub 15 if (o1.start != o2.start) 16 return o1.start < o2.start ? -1 : 1; 17 else if (o1.end != o2.end) 18 return o1.end < o2.end ? -1 : 1; 19 else 20 return 0; 21 } 22 } 23 24 public List<Interval> merge(List<Interval> intervals) { 25 List<Interval> result = new ArrayList<Interval>(); 26 27 if (intervals.size() == 0) 28 return result; 29 if (intervals.size() == 1) 30 return intervals; 31 32 Collections.sort(intervals, new MyCompare()); 33 Interval last=intervals.get(0); 34 int N=intervals.size(); 35 for(int i=1;i<N;++i){ 36 if(intervals.get(i).start>last.end){ 37 result.add(new Interval(last.start,last.end)); 38 last=intervals.get(i); 39 }else{ 40 last.end=Math.max(intervals.get(i).end, last.end); 41 } 42 } 43 result.add(last); 44 return result; 45 } 46 }