forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge.java
More file actions
30 lines (27 loc) · 979 Bytes
/
Merge.java
File metadata and controls
30 lines (27 loc) · 979 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package bit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Merge {
public int[][] merge(int[][] intervals){
if (intervals.length <= 1) return intervals;
Arrays.sort(intervals,(i1,i2) -> Integer.compare(i1[0],i2[0]));
List<int[]> result = new ArrayList<>();
int[] newInterval = intervals[0];
result.add(newInterval);
for (int[] interval : intervals){
if (interval[0] <= newInterval[1]) newInterval[1] = Math.max(newInterval[1],interval[1]);
else {
newInterval = interval;
result.add(newInterval);
}
}
return result.toArray(new int[result.size()][]);
}
public static void main(String[] args) {
int[][] intervals = {{1,3},{2,6},{8,10},{15,18}};
Merge merge = new Merge();
int[][] r = merge.merge(intervals);
System.out.println(Arrays.deepToString(r));
}
}