[leetcode]56. Merge Intervals归并区间

时间:2022-11-15 20:13:49

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

题意:

给定一些区间,将重叠部分合并。

思路:

将原interval集合里,给定区间按照start开头值的从小到大排序

建一个新的interval集合

遍历原interval集合的每个区间,

若cur.start > pre.end 则说明没有重叠,扔到新的interval集合去。

否则,有重叠,则更新之前区间.end的长度

代码:

 class Solution {
public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, (o1, o2)-> o1.start - o2.start); List<Interval> result = new ArrayList<>(); Interval pre = null;
for(Interval cur : intervals){
if(pre == null || cur.start > pre.end){
result.add(cur);
pre = cur;
}else{
pre.end = Math.max(pre.end, cur.end);
}
}
return result;
}
}