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: 先按start从小到大排序。然后比较cur.start与prev.end,如果prev.end < cur.start,说明不用合并,直接加入;否则把prev.end改为Math.max(prev.end, cur.end)
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null || intervals.size() < 2) {
return intervals;
}
Collections.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
List<Interval> ans = new ArrayList<>();
for (Interval cur : intervals) {
if (ans.size() == 0 || ans.get(ans.size() - 1).end < cur.start) {
ans.add(cur);
} else {
ans.get(ans.size() - 1).end = Math.max(ans.get(ans.size() - 1).end, cur.end);
}
}
return ans;
}