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.
class Solution { public int[][] merge(int[][] intervals) { int l = intervals.length; if(l == 0 || l == 1) return intervals; int[][] res = insert(new int[][]{}, intervals[0]); for(int i = 1; i < intervals.length; i++){ res = insert(res, intervals[i]); } return res; } public int[][] insert(int[][] intervals, int[] newInterval) { List<int[]> resu = new ArrayList(); int s = newInterval[0], e = newInterval[1]; int i = 0; //add all intervals which are before the new Interval while(i < intervals.length && intervals[i][1] < s){ resu.add(intervals[i++]); } //ensure all of the intervals are merged based on the start and end time of the newInterval while(i < intervals.length && intervals[i][0] <= e){ s = Math.min(s, intervals[i][0]); e = Math.max(e, intervals[i][1]); i++; } //Add merged interval resu.add(new int[]{s, e}); //Add the remaining intervals while(i < intervals.length) resu.add(intervals[i++]); int j = 0; int[][] res = new int[resu.size()][2]; for(int[] tmp: resu){ res[j++] = tmp; } return res; } }
使用57题作为method即可,注意parameters