以數(shù)組 intervals 表示若干個(gè)區(qū)間的集合,其中單個(gè)區(qū)間為 intervals[i] = [starti, endi] 泞边。請你合并所有重疊的區(qū)間袖肥,并返回一個(gè)不重疊的區(qū)間數(shù)組障本,該數(shù)組需恰好覆蓋輸入中的所有區(qū)間
https://leetcode-cn.com/problems/merge-intervals/
示例1:
輸入:intervals = [[1,3],[2,6],[8,10],[15,18]]
輸出:[[1,6],[8,10],[15,18]]
解釋:區(qū)間 [1,3] 和 [2,6] 重疊, 將它們合并為 [1,6]
示例2:
輸入:intervals = [[1,4],[4,5]]
輸出:[[1,5]]
解釋:區(qū)間 [1,4] 和 [4,5] 可被視為重疊區(qū)間员凝。
提示:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
Java解法
思路:
- 依次遍歷,判斷其他區(qū)間與當(dāng)前區(qū)間是否存在重疊瞧掺,若存在進(jìn)行合并跳出耕餐,再進(jìn)行遍歷
- 若不存在加入輸出數(shù)組中
- 用到遞歸,所以空間占用并不是很高效
package sj.shimmer.algorithm.m2;
import java.util.ArrayList;
import java.util.List;
/**
* Created by SJ on 2021/2/27.
*/
class D34 {
public static void main(String[] args) {
int[][] merge = merge(new int[][]{{1, 3}, {2, 6}, {8, 10}, {15, 18}});
int[][] merge1 = merge(new int[][]{{1, 4}, {4, 5}});
int[][] merge2 = merge(new int[][]{{2,3},{2,2},{3,3},{1,3},{5,7},{2,2},{4,6}});
for (int[] ints : merge2) {
for (int anInt : ints) {
System.out.print(anInt);
System.out.print(",");
}
System.out.println("---");
}
}
public static int[][] merge(int[][] intervals) {
List<int[]> list = new ArrayList<>();
for (int[] interval : intervals) {
list.add(interval);
}
List<int[]> merge = merge(list, 0);
return merge.toArray(new int[merge.size()][2]);
}
public static List<int[]> merge(List<int[]> lists,int index) {
if (lists != null&&lists.size()>index) {
int[] compare = lists.get(index);
for (int i = index+1; i < lists.size(); i++) {
int[] interval = lists.get(i);
//無重疊情況
if (interval[0]>compare[1]||interval[1]<compare[0]) {
if (i==lists.size()-1) {
return merge(lists,++index);
}
continue;
}else {
compare[0]=Math.min(interval[0],compare[0]);
compare[1]=Math.max(interval[1],compare[1]);
lists.remove(interval);
return merge(lists,index);
}
}
}
return lists;
}
}
官方解
https://leetcode-cn.com/problems/merge-intervals/solution/he-bing-qu-jian-by-leetcode-solution/
-
排序
先按左側(cè)邊界做升序排序辟狈,這樣可以合并的區(qū)間一定是連續(xù)的
-
然后按區(qū)間重疊方式計(jì)算要加入的數(shù)據(jù)
public int[][] merge(int[][] intervals) { if (intervals.length == 0) { return new int[0][2]; } Arrays.sort(intervals, new Comparator<int[]>() { public int compare(int[] interval1, int[] interval2) { return interval1[0] - interval2[0]; } }); List<int[]> merged = new ArrayList<int[]>(); for (int i = 0; i < intervals.length; ++i) { int L = intervals[i][0], R = intervals[i][1]; if (merged.size() == 0 || merged.get(merged.size() - 1)[1] < L) { merged.add(new int[]{L, R}); } else { merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], R); } } return merged.toArray(new int[merged.size()][]); }
時(shí)間復(fù)雜度:O(n log n)
空間復(fù)雜度:O(log n)