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].
Example 2:
Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
题目意思:查看两个区间有无重叠,如果有则用两个区间之间的 最大值和最小值加入结果。
首先对数组进行排序,排序后进行对区间进行比较:
class Solution {
public int[][] merge(int[][] intervals) {
if(intervals ==null || intervals.length <=1) {
return intervals;
}
List<int[]>tmp = new ArrayList<>();
Arrays.sort(intervals, new Comparator<int[]> () {
@Override
public int compare(int[] i1, int[] i2) {
return i1[0] - i2[0];
}
});
tmp.add(intervals[0]);
for(int i=1;i<intervals.length;i++) {
int[] before =tmp.get(tmp.size()-1);
if(canMerge(before,intervals[i])) {
tmp.remove(tmp.size()-1);
tmp.add(new int[] {Math.min(before[0],intervals[i][0]),Math.max(before[1],intervals[i][1])});
}else {
tmp.add(intervals[i]);
}
}
int[][] res = new int[tmp.size()][];
for(int index = 0;index<tmp.size() ;index++) {
res[index] = tmp.get(index);
}
return res;
}
public boolean canMerge(int[] a,int[] b) {
if(a[0] == b[0]) {
return true;
}else if(a[0] < b[0]) {
if(a[1] >= b[0]) {
return true;
}else {
return false;
}
}
return false;
}
}