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].
tag: 对象排序comparator, List转换成数组
/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ // list 与数组相互转换 public class Solution { public List<Interval> merge(List<Interval> intervals) { List<Interval> result = new ArrayList<Interval>(); if(intervals == null || intervals.size() == 0) { return result; } int size = intervals.size(); Interval[] intervalArr = intervals.toArray(new Interval[size]); Arrays.sort(intervalArr, new Comparator<Interval>(){ public int compare(Interval interval1, Interval interval2) { return interval1.start - interval2.start; } }); Interval mover = intervalArr[0]; for(int i = 1; i < size; i++) { if(mover.end < intervalArr[i].start ) { result.add(mover); mover = intervalArr[i]; } else { mover.end = Math.max(mover.end, intervalArr[i].end); } } result.add(mover); return result; } }