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]);
}
}