1. Title Description
Given a collection of intervals, merge all overlapping intervals.
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].
Second, the solution
Method 1: Greed
Wrong idea: I originally wanted to directly use end to record the value of the maximum end position in the first i-1 intervals of the i-th loop, and then use it to decide whether to merge the intervals:
- If they do not coincide, add the current array directly, followed by the new end value and endi subscript.
- Otherwise, let the right endpoint of the last element in the list be set to
max(end, inte[i][0])
But there is a problem with this: when such a broken thing appears, it explodes ...[[1,4],[0,5]]
public int[][] merge(int[][] inte) {
if (inte.length <= 1) {
return inte;
}
List<int[]> list = new LinkedList<>();
int end = inte[0][1], endi = 0;
Arrays.sort(inte, (e1, e2) -> e1[0] - e2[0]);
list.add(inte[0]);
for (int i = 1; i < inte.length; i++) {
if (end < inte[i][0]) { //无交集
list.add(inte[i]);
end = inte[i][1];
endi = i;
} else if (end >= inte[i][0]){//交集
list.get(endi)[1] = Math.max(inte[i][1], end);
}
}
int[][] res = new int[list.size()][2];
int i = 0;
for (int[] arr : list) {
res[i++] = arr;
}
return res;
}
Think about it, or judge the trouble on the linked list directly.
public int[][] merge(int[][] inte) {
if (inte.length == 1) {
return inte;
}
List<int[]> list = new ArrayList<>();
Arrays.sort(inte, (e1, e2) -> e1[0] - e2[0]);
for (int i = 0; i < inte.length; i++) {
if (list.isEmpty() || list.get(list.size()-1)[1] < inte[i][0]) {
list.add(inte[i]);
} else {
int end = list.get(list.size()-1)[1];
list.get(list.size()-1)[1] = Math.max(end, inte[i][1]);
}
}
int[][] res = new int[list.size()][2];
int i = 0;
for (int[] arr : list) {
res[i++] = arr;
}
return res;
}
Complexity analysis
- time complexity: ,
- Space complexity: ,