For example,
Given
[1,3],[2,6],[8,10],[15,18],return
[1,6],[8,10],[15,18].
Write a comparator to sort the intervals according to their start time. Then from the first interval, we do following:
- initialize the current merged interval using the first interval
- if the current interval intersect with the current merged interval, then we update the endTime of the current interval
- otherwise we insert the current merged interval to the result, and update the current merged interval using the current interval
public class myComparator implements Comparator<Interval> {
public int compare(Interval i1, Interval i2) {
return i1.start - i2.start;
}
}
public List<Interval> merge(List<Interval> intervals) {
if(intervals.size() == 0)
return intervals;
List<Interval> res = new ArrayList<Interval>();
Collections.sort(intervals, new myComparator());
int startTime = intervals.get(0).start, endTime = intervals.get(0).end;
for(Interval i : intervals) {
if(i.start > endTime) {
Interval interval = new Interval(startTime, endTime);
res.add(interval);
startTime = i.start;
endTime = i.end;
}
else {
endTime = Math.max(endTime, i.end);
}
}
Interval interval = new Interval(startTime, endTime);
res.add(interval);
return res;
}
没有评论:
发表评论