-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path56. Merge Intervals.java
More file actions
32 lines (32 loc) · 1.05 KB
/
56. Merge Intervals.java
File metadata and controls
32 lines (32 loc) · 1.05 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
31
32
// }
// int finalArray[][] = new int[result.size()][2];
// int count = 0;
// for(Interval temp : result){
// finalArray[count][0] = temp.start;
// finalArray[count][1] = temp.end;
// count++;
// }
// return finalArray;
// }
// }
//*************************Another approach **********************************
class Solution {
public int[][] merge(int[][] intervals) {
Collections.sort(Arrays.asList(intervals),(a,b)-> a[0]-b[0]);
LinkedList<int[]> result = new LinkedList<>();
for(int[] interval : intervals){
if(result.isEmpty() || result.getLast()[1]< interval[0]){
result.add(interval);
}
else{
result.getLast()[1] = Math.max(result.getLast()[1], interval[1]);
}
}
return result.toArray(new int[result.size()][]);
}
}