Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
思路: 题目的意思是归并给定的区间。 想象一下,如果所有的区间都是在数轴上按照顺序排列的话,那么归并区间就似乎不那么难了,可以按照顺序归并。
先将所有区间进行排序,然后在按照顺序归并
对于以下区间 [1,3] , [2,6] , [8,10] , [15,18] ,用last表示上一次归并到哪一个区间了,last初始化为[1,3]
- last 与 [2,6] 有交集,所以进行归并 得到last 为 【1,6】
- last 为 【1,6】,但【1,6】 与【8,10】没有交集,所以last归并完了,将【1,6】加入结果集中,更新last为【8,10】
- last为【8,10】,但【8,10】 与【15,18】 没有交集,也就是last归并完了,将【8,10】加入结果集中,更新last为【15,18】
- last为【15,18】 后面没有区间与之归并,所以最后也将last加入结果集中。
- 所以最后的结果为 [1,6],[8,10],[15,18].
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
int n=intervals.size();
List<Interval> res=new ArrayList<Interval>();
if(n<=0) return res;
Collections.sort(intervals, new IntervalComparator());
Interval last=intervals.get(0);
for(int i=1;i<intervals.size();i++)
{
Interval temp =intervals.get(i);
if(temp.start>last.end)
{
res.add(new Interval(last.start,last.end));
last=temp;
}else {
last.end= last.end > temp.end ? last.end : temp.end;
}
}
res.add(last);
return res;
}
static class IntervalComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Interval i1 = (Interval) o1;
Interval i2 = (Interval) o2;
if (i1.start < i2.start)
return -1;
else if (i1.start == i2.start) {
if (i1.end > i2.end)
return 1;
else if (i1.end == i2.end)
return 0;
else
return -1;
} else
return 1;
}
}
}