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的长度
代码:
1 class Solution { 2 public List<Interval> merge(List<Interval> intervals) { 3 Collections.sort(intervals, (o1, o2)-> o1.start - o2.start); 4 5 List<Interval> result = new ArrayList<>(); 6 7 Interval pre = null; 8 for(Interval cur : intervals){ 9 if(pre == null || cur.start > pre.end){ 10 result.add(cur); 11 pre = cur; 12 }else{ 13 pre.end = Math.max(pre.end, cur.end); 14 } 15 } 16 return result; 17 } 18 }