-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
26 lines (22 loc) · 829 Bytes
/
solution.java
File metadata and controls
26 lines (22 loc) · 829 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
class Solution {
public int[][] merge(int[][] intervals) {
//Sort intervals based on start time
Arrays.sort(intervals, (int[] x, int[] y) -> Integer.compare(x[0], y[0]));
//Result list
LinkedList<int[]> result = new LinkedList<>();
result.add(intervals[0]);
for(int[] intv : intervals){
int start = intv[0];
int end = intv[1];
int[] last = result.getLast();
//Merge intervals if start is not larger then previous end
if(start <= last[1]){
last[1] = Math.max(last[1], end);
} else {
//Add new interval to result
result.add(intv);
}
}
return result.toArray(new int[result.size()][]);
}
}