forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_56.java
29 lines (25 loc) · 981 Bytes
/
_56.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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class _56 {
public static class Solution1 {
/**
* My completely original solution on 10/12/2021.
*/
public int[][] merge(int[][] intervals) {
List<int[]> list = new ArrayList<>();
Arrays.sort(intervals, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(b[1], a[1]));//to avoid integer subtraction overflow
for (int i = 0; i < intervals.length; i++) {
int start = intervals[i][0];
int end = intervals[i][1];
while (i + 1 < intervals.length && intervals[i + 1][0] <= end) {
end = Math.max(intervals[i + 1][1], end);
i++;
}
list.add(new int[]{start, end});
}
return list.toArray(new int[list.size()][2]);
}
}
}