-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeIntervalsII.java
More file actions
39 lines (35 loc) · 983 Bytes
/
MergeIntervalsII.java
File metadata and controls
39 lines (35 loc) · 983 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
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Stack;
/**
* 56. 合并区间
*/
public class MergeIntervalsII {
public int[][] merge(int[][] intervals) {
// 从小到大排序
LinkedList<int[]> ll = new LinkedList<>();
Arrays.sort(intervals, (a,b) -> {
return a[0]-b[0];
});
int left=intervals[0][0], right=intervals[0][1];
for(int[] t: intervals){
if(t[0]<=left && left<=t[1]){
left = t[0];
}
if(t[0]<=right && right<=t[1]){
right = t[1];
}
if(t[0]>right || left>t[1]){
ll.add(new int[]{left, right});
left = t[0];
right = t[1];
}
}
ll.add(new int[]{left, right});
int[][] res = new int[ll.size()][2];
for(int i=0; i<ll.size(); i++){
res[i] = ll.get(i);
}
return res;
}
}