Description:
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:
Just sort the interval list, begin time has a higher priority, and if they are the same for two intervals, then sort this list with its end time, and later end time will have higher proirity. After sorting like this:
<1,9>, <1,4>, <1,3>, <2,9>, <2,2>, <10,11>
Then iterate from the first one, use an index 'startTime' and 'endTime' to keep the current new interval's start and end. And if current endTime is bigger than listnode's start, end this current new interval, and start a new one.
import java.io.*;
import java.util.*;
class Solution {
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null)
return intervals;
intervals.add(new Interval(-1, -1));
Comparator<Interval> comp = new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
if (a.end == b.end) {
return a.start - b.start;
}
return b.end - a.end;
}
};
Collections.sort(intervals, comp);
LinkedList<Interval> neoList = new LinkedList<Interval>();
int startTime = intervals.get(0).start;
int endTime = intervals.get(0).end;
Interval interval;
for (Iterator<Interval> ite = intervals.iterator(); ite.hasNext();) {
interval = ite.next();
if (interval.end < startTime) {
neoList.add(new Interval(startTime, endTime));
startTime = interval.start;
endTime = interval.end;
} else {
startTime = Math.min(startTime, interval.start);
}
}
return neoList;
}
}
class Interval {
int start, end;
public Interval(int a, int b) {
start = a;
end = b;
}
}