Q:
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
A:
Use list to add intervals
if the current interval overlaps the previous interval, merge this two intervals.
Otherwise, add the interval to the list directly.
Finally, convert the list to Array.
class Solution {
public int[][] merge(int[][] intervals) {
if(intervals.length==0) return new int[0][2];
Arrays.sort(intervals, new Comparator<int[]>(){
public int compare(int[] a, int[] b){
return a[0]-b[0];
}
}
);
List<int[]> list = new ArrayList<int[]>();
list.add(intervals[0]);
for(int[] i :intervals){
if(i[0]<=list.get(list.size()-1)[1]){
list.get(list.size()-1)[1] = Math.max(list.get(list.size()-1)[1], i[1]);
}else{
list.add(i);
}
}
return list.toArray(new int[list.size()][2]);
}
}
本文介绍了一种有效的合并区间算法,该算法将输入的一系列区间进行合并,并返回一系列不重叠的区间。通过排序和列表操作,可以高效地解决区间合并问题。
298

被折叠的 条评论
为什么被折叠?



