-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMergeInterval.java
32 lines (27 loc) · 937 Bytes
/
MergeInterval.java
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
package leetcode.interval;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class MergeInterval {
public int[][] merge(int[][] intervals) {
if (intervals == null || intervals.length == 0) {
return intervals;
}
// First sort the intervals by their starting points.
Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
// Then finds all the merged intervals.
List<int[]> result = new ArrayList<>();
int[] current = intervals[0];
result.add(current);
for (int[] interval: intervals) {
if (interval[0] <= current[1]) {
current[1] = Math.max(current[1], interval[1]);
} else {
current = interval;
result.add(current);
}
}
return result.toArray(new int[result.size()][]);
}
}