解题思路
首先对当前的intervals进行排序,用Collections.sort(intervals, (o1,o2)->Integer.compare())
记录上一个的头尾
和上一个进行比较
class Solution {
public List<Interval> merge(List<Interval> intervals) {
if(intervals.size() <= 1){
return intervals;
}
Collections.sort(intervals, (o1,o2)->Integer.compare(o1.start,o2.start));
int lastStart = intervals.get(0).start;
int lastEnd = intervals.get(0).end;
List<Interval> res = new LinkedList<>();
for(Interval current : intervals){
if(current.start > lastEnd){
res.add(new Interval(lastStart,lastEnd));
lastEnd = current.end;
lastStart = current.start;
} else {
lastEnd = Math.max(current.end, lastEnd);
}
}
res.add(new Interval(lastStart,lastEnd));
return res;
}
}
本文介绍了一种有效的区间合并算法,该算法通过先对输入的区间列表进行排序,然后逐一比较并合并重叠区间来实现。文章提供了完整的Java实现代码,并详细解释了每一步的处理逻辑。
2813

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



