Given a collection of intervals, merge all overlapping intervals.
For example,
Given
return
Given
[1,3],[2,6],[8,10],[15,18],return
[1,6],[8,10],[15,18].
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
class IntervalComparator implements Comparator{
public int compare(Interval a, Interval b){
return a.start - b.start;
}
}
public List merge(List intervals) {
List ret = new ArrayList();
int len = intervals.size();
if(0 == len)
return ret;
Collections.sort(intervals, new IntervalComparator());
Interval m = intervals.get(0);
for(int i = 1; i < len; ++i){
Interval c = intervals.get(i);
if(m.end >= c.start)
{
m.end = Math.max(m.end, c.end);
}else{
ret.add(m);
m = c;
}
}
ret.add(m);
return ret;
}
}
No comments:
Post a Comment