Thought:
First sort by the start time, then merge.
Code:
public class Solution {
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
if (intervals.size() == 0) return intervals;
Collections.sort(intervals, BYSTART);
ArrayList<Interval> ret = new ArrayList<Interval>();
int s = intervals.get(0).start;
int e = intervals.get(0).end;
for ( Interval itv : intervals) {
if (e >= itv.start) e = Math.max(e, itv.end);
else {
ret.add(new Interval(s, e));
s = itv.start;
e = itv.end;
}
}
ret.add(new Interval(s, e));
return ret;
}
private static final Comparator<Interval> BYSTART = new Comparator<Interval>(){
public int compare (Interval i, Interval j) {
return new Integer(i.start).compareTo(new Integer(j.start));
}
};
}
No comments:
Post a Comment