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]
.
/** * 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; } * } */ public class Solution { private class IntervalComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { return a.start - b.start; } } public ArrayList<Interval> merge(ArrayList<Interval> intervals) { if (intervals.size()<=1) { return intervals; } Collections.sort(intervals, new IntervalComparator()); ArrayList<Interval> result = new ArrayList<Interval>(); Interval pre = intervals.get(0); for (int i=1;i<intervals.size();i++) { Interval current = intervals.get(i); if (pre.end >= current.start) { //修正PRE 但是不能立刻添加到结果中 pre.end = Math.max(current.end, pre.end); continue; } result.add(pre); pre = current; } result.add(pre); return result; } }