給出一個區間的集合,請合併全部重疊的區間。
示例 1:
輸入: [[1,3],[2,6],[8,10],[15,18]]
輸出: [[1,6],[8,10],[15,18]]
解釋: 區間 [1,3] 和 [2,6] 重疊, 將它們合併爲 [1,6].
示例 2:
輸入: [[1,4],[4,5]]
輸出: [[1,5]]
解釋: 區間 [1,4] 和 [4,5] 可被視爲重疊區間。ui
來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/merge-intervalscode
class Solution { public int[][] merge(int[][] intervals) { if (null==intervals||intervals.length==0){ return intervals; } int length = intervals.length; quickSort(intervals,0, length-1); List<int[]> result = new ArrayList<>(); result.add(intervals[0]); for (int i=1;i<length;i++) { int index = result.size() - 1; int[][] combine = combine(result.get(index),intervals[i]); if (combine.length==1){ result.remove(index); result.add(combine[0]); }else{ result.add(intervals[i]); } } int size = result.size(); int[][] r = new int[size][2]; for (int i=0;i<size;i++) { r[i] = result.get(i); } return r; } private int[][] combine(int[] a,int[] b){ int al=a[0],ar=a[1],bl=b[0],br=b[1]; if (ar>=bl ||bl<=ar){ int[][] r = new int[1][2]; r[0]=new int[]{al<bl?al:bl,br>ar?br:ar}; return r; }else{ int[][] r = new int[2][2]; r[0]=a; r[1]=b; return r; } } private void quickSort(int[][] arr,int left,int right){ if (left>=right){ return; } int[] mid = arr[left]; int i=left; int j=right; while (i<j){ while (arr[j][0]>=mid[0]&&i<j){ j--; } while (arr[i][0]<=mid[0]&&i<j){ i++; } if (i<j){ int[] tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } arr[left]=arr[i]; arr[i]=mid; quickSort(arr,left,i-1); quickSort(arr,i+1,right); } }