以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi]。请你合并所有重叠的区间,并返回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。
示例 1:
输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
输出:[[1,6],[8,10],[15,18]]
解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].示例 2:
输入:intervals = [[1,4],[4,5]]
输出:[[1,5]]
解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。提示:
- 1 <= intervals.length <= 104
- intervals[i].length == 2
- 0 <= starti <= endi <= 104
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/merge-intervals
class Solution {
public int[][] merge(int[][] intervals) {
if(intervals.length <= 1 ) return intervals;
quickSort(0 , intervals.length - 1 , intervals );
int start = -1 , end = -1 ;
List<int[]> list = new ArrayList<>() ;
for(int i = 0 ; i < intervals.length ; i ++) {
if( start == -1 || end == -1 ){
start = intervals[ i ] [ 0 ] ;
end = intervals[ i ] [ 1 ] ;
}else if( intervals[ i ] [ 0 ] <= end ){
start = start < intervals[ i ] [ 0 ] ? start : intervals[ i ] [ 0 ] ;
end = end > intervals[ i ] [ 1 ] ? end : intervals[ i ] [ 1 ] ;
}else{
list.add( new int[] { start , end } ) ;
start = -1 ;
end = -1 ;
i --;
}
}
if( start != -1 && end != -1 )
list.add( new int[] { start , end } ) ;
int[][] res = new int[ list .size() ][ 2 ] ;
for( int i = 0 ; i < list.size() ; i ++ ) res[ i ] = list.get ( i ) ;
return res;
}
public void quickSort( int left , int right , int[][] rows ) {
if( left >= right ) return ;
int temp = rows [ left ][ 0 ] ;
int low = left ;
int hight = right ;
while( low < hight ) {
while( low < hight && rows[ hight ][ 0 ] >= temp ) hight--;
while( low < hight && rows[ low ][ 0 ] <= temp ) low++;
if( low < hight ) {
int tmp = rows[ low ][ 0 ] ;
rows[ low ][ 0 ] = rows [ hight ][ 0 ] ;
rows[ hight ][ 0 ] = tmp ;
tmp = rows[ low ][ 1 ] ;
rows[ low ][ 1 ] = rows [ hight ][ 1 ] ;
rows[ hight ][ 1 ] = tmp ;
}
}
rows [ left ][ 0 ] = rows[ low ][ 0 ];
rows [ low ][ 0 ] = temp ;
temp = rows [ left ][ 1 ] ;
rows [ left ][ 1 ] = rows[ low ][ 1 ];
rows [ low ][ 1 ] = temp ;
quickSort ( left , hight -1 ,rows );
quickSort ( hight + 1 , right , rows ) ;
}
}