-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeIntervals.java
More file actions
30 lines (28 loc) · 1.01 KB
/
MergeIntervals.java
File metadata and controls
30 lines (28 loc) · 1.01 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
import java.util.Arrays;
import java.util.LinkedList;
/**
* Leetcode problem #56, Merge Intervals
* https://leetcode.com/problems/merge-intervals/description/
*/
public class MergeIntervals {
public static void main(String[] args) {
int[][] intervals = { { 1, 3 }, { 2, 6 }, { 8, 10 }, { 15, 18 } };
int[][] mergedIntervals = merge(intervals);
System.out.println(Arrays.deepToString(mergedIntervals));
}
public static int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
LinkedList<int[]> list = new LinkedList<>();
int[] current = intervals[0];
for (int i = 1; i < intervals.length; i++) {
if (current[1] >= intervals[i][0]) {
current[1] = Math.max(current[1], intervals[i][1]);
} else {
list.add(current);
current = intervals[i];
}
}
list.add(current);
return list.toArray(new int[list.size()][]);
}
}