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 {
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null || intervals.size() <= 1) {
return intervals;
}
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
// TODO Auto-generated method stub
return o1.start - o2.start;
}
});
List<Interval> res = new ArrayList<>();
Interval pre = intervals.get(0);
for (int i = 1; i < intervals.size(); i++) {
Interval cur = intervals.get(i);
if (pre.end >= cur.start) {
Interval merge = new Interval(pre.start, Math.max(pre.end, cur.end));
pre = merge;
} else {
res.add(pre);
pre = cur;
}
}
res.add(pre);
return res;
}
}
本文介绍了一种有效的算法来合并一系列可能存在重叠的区间。通过排序和遍历的方式,该算法可以将所有重叠的区间合并为一个区间,最终返回一个没有重叠的区间列表。例如,给定区间 [1,3],[2,6],[8,10],[15,18],合并后的结果为 [1,6],[8,10],[15,18]。

被折叠的 条评论
为什么被折叠?



