public List<Interval> merge(List<Interval> intervals) {
// write your code here
List<Interval> res= new ArrayList<Interval>();
if(intervals.size() == 0 || intervals == null)
return res;
Collections.sort(intervals, new IntervalComparator());
Interval first = intervals.get(0);
for(int i = 1; i < intervals.size(); i++) {
Interval cur = intervals.get(i);
if(cur.start <= first.end) {
first.end = Math.max(cur.end, first.end);
}else{
res.add(first);
first = cur;
}
}
res.add(first);
return res;
}
class IntervalComparator implements Comparator{
public int compare(Object o1, Object o2){
Interval i1 = (Interval)o1;
Interval i2 = (Interval)o2;
return i1.start - i2.start;
}
}
Leave A Comment