56. Merge Intervals (JAVA)
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.
涉及:
- 数组的截取与拷贝
- 重写Array.sort的compare函数(注意:jdk1.7以后,必须要定义相等的情况返回0,否则会报Runtime error)
class Solution { public int[][] merge(int[][] intervals) { if(intervals.length == 0) return intervals; Arrays.sort(intervals,0, intervals.length, new ArrayComparator()); int curIndex = 0; for(int i = 1; i < intervals.length; i++){ if(intervals[curIndex][1] >= intervals[i][1]){ //only reserve intervals[i-1] continue; } else if(intervals[curIndex][1] >= intervals[i][0]){//integrate intervals[curIndex][1] = intervals[i][1]; } else{ //no interval curIndex++; intervals[curIndex][0] = intervals[i][0]; intervals[curIndex][1] = intervals[i][1]; } } curIndex++; int[][] ret = new int[curIndex][2]; System.arraycopy(intervals, 0, ret, 0, curIndex); return ret; } } class ArrayComparator implements Comparator{ public int compare(Object o1, Object o2){ int[] a = (int[]) o1; int[] b = (int[]) o2; if(a[0] > b[0]) return 1;//ascending order else if(a[0] < b[0]) return -1; else return 0; } }