-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeIntervals.java
More file actions
47 lines (39 loc) · 1.34 KB
/
Copy pathMergeIntervals.java
File metadata and controls
47 lines (39 loc) · 1.34 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.*;
public class MergeIntervals {
static int[][] process(int[][] in) {
List<int[]> result = new ArrayList<>();
for (int i = 0; i<in.length; i++) {
int start = in[i][0];
int end = in[i][1];
if (!result.isEmpty() && end <= result.getLast()[1]) {
// if this range end earlier that what we already have, ignore it.
continue;
}
for (int j = i+1; j<in.length; j++) {
if (in[j][0] <= end) {
end = Math.max(end, in[j][1]); // merge this in
} else {
break; // don't merge this one, and exit this inner loop
}
}
result.add(new int[]{start,end});
}
return result.stream().toArray(int[][]::new);
}
void main() {
int[][] in = {
{1,3},
{2,9},
{3,5},
{8,10},
{15,18}};
int[][] expected = {
{1,10},
{15,18}};
int[][] merged = process(in);
IO.println("In = " + Arrays.deepToString(in));
IO.println("Expected = " + Arrays.deepToString(expected));
IO.println("Merged = " + Arrays.deepToString(merged));
IO.println("Equal? " + Arrays.deepEquals(expected, merged));
}
}