-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy path56-merge-intervals.java
More file actions
25 lines (24 loc) · 903 Bytes
/
Copy path56-merge-intervals.java
File metadata and controls
25 lines (24 loc) · 903 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
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));
ArrayList<int[]> res = new ArrayList<>();
int prevS = intervals[0][0];
int prevE = intervals[0][1];
for (int i = 1; i < intervals.length; i++) {
int curS = intervals[i][0];
int curE = intervals[i][1];
if (prevE < curS) {
res.add(new int[]{prevS, prevE});
prevS = curS;
prevE = curE;
} else {
prevE = Math.max(prevE, curE);
}
}
res.add(new int[]{prevS, prevE});
return res.toArray(new int[res.size()][2]);
}
}
// time O(nlogn)
// space O(n), due to output and sort
// using array and line sweep and compare two intervals each round and sort