The topic is from LeetCode
Other solutions or source code can be accessed: tongji4m3
description
Given a set of intervals, please merge all overlapping intervals.
Example 1:
输入: intervals = [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
Example 2:
输入: intervals = [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
prompt:
intervals[i][0] <= intervals[i][1]
Ideas
按区间的第一个元素排序
for i in N:
lo=intervals[i][0];
hi=intervals[i][1];
while(i+1<N && hi>=intervals[i+1][0]) hi=intervals[++i][1];//扩展该区间
result.add((lo,hi));
detail
- The length of the interval should be the largest of the two combined intervals
- Pay attention to the conversion operations of collections and arrays
Code
public int[][] merge(int[][] intervals)
{
int N = intervals.length;
List<int[]> result = new LinkedList<>();
//按第一个元素排序
Arrays.sort(intervals, (a,b) -> a[0]-b[0]);
for (int i = 0; i < N; i++)
{
int lo=intervals[i][0];
int hi=intervals[i][1];
while(i+1<N && hi>=intervals[i+1][0])
{
++i;//表明把下一个区间也纳入到了本区间里了
hi=Math.max(hi,intervals[i][1]);//look 扩展该区间,选最大的一个
}
result.add(new int[]{
lo, hi});
}
return (int[][]) result.toArray(new int [result.size()][2]);
}
Complexity analysis
time complexity
O (N log N) O (N log N) O ( N l o g N ) , mainly the sorting overhead, the other is the scanning of N overhead
Space complexity
O (log N) O (logN) O ( l o g N ) , calculate the extra space overhead outside the answer, here is the space complexity required for sorting