-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08_Merge_Intervals.java
35 lines (29 loc) · 1.02 KB
/
08_Merge_Intervals.java
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
import java.util.* ;
import java.io.*;
/*******************************************************
Following is the Interval class structure
class Interval {
int start, int finish;
Interval(int start, int finish) {
this.start = start;
this.finish = finish;
}
}
*******************************************************/
import java.util.List;
import java.util.ArrayList;
public class Solution {
public static List<Interval> mergeIntervals(Interval[] intervals) {
Arrays.sort(intervals, Comparator.comparingInt(a -> a.start));
List<Interval> res=new ArrayList<>();
for(int i=0;i<intervals.length;i++){
if(res.isEmpty() || intervals[i].start>res.get(res.size()-1).finish){
res.add(intervals[i]);
}
else{
res.get(res.size()-1).finish=Math.max(res.get(res.size()-1).finish,intervals[i].finish);
}
}
return res;
}
}