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]
.
The follow up question is can you not use extra space?
So the answer here is not using extra space.
First write the Collections.sort comparator to sort the intervals and then compare each two intervals see if there's an overlap.
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null) return null;
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval a, Interval b) {
if (a.start == b.start) {
return b.end - a.end;
}
return a.start - b.start;
}
});
int i = 0;
while (i < intervals.size() - 1) {
Interval a = intervals.get(i), b = intervals.get(i + 1);
if (a.end >= b.start) {
a.end = Math.max(a.end, b.end);
intervals.remove(i + 1);
} else {
i++;
}
return intervals;
}
}