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]
.
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null || intervals.size() <= 1) return intervals;
Collections.sort(intervals, (o1, o2) -> o1.start - o2.start);
List<Interval> res = new ArrayList<>();
Interval curr = intervals.get(0);
for (int i = 1; i < intervals.size(); i++) {
if (intervals.get(i).start <= curr.end) { // merged
curr.end = Math.max(curr.end, intervals.get(i).end);
} else {
res.add(curr);
curr = intervals.get(i);
}
}
res.add(curr);
return res;
}