题目描述:
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].
先将给定的intervals排序,然后从第一个开始,逐个比较,插入前面的interval,所以这个时候一定要注意最后一个interval,要单独拿出来讨论
public List<Interval> merge(List<Interval> intervals) {
List<Interval> list=new ArrayList<Interval>();
int n=intervals.size();
if(n<=1)
return intervals;
intervals.sort((o1,o2)->{
if(o1.start>o2.start||(o1.start==o2.start&&o1.end>o2.end))
return 1;
else if(o1.start<o2.start||(o1.start==o2.start&&o1.end<o2.end))
return -1;
else
return 0;
});
Interval lastInterval=intervals.get(0);
for (int i = 1; i < n; i++) {
if(intervals.get(i).start>lastInterval.end){
list.add(lastInterval);
lastInterval=intervals.get(i);
}else{
lastInterval.end=lastInterval.end>intervals.get(i).end?lastInterval.end:intervals.get(i).end;
}
}
//单独讨论最后一个interval
if(intervals.get(n-1).start>lastInterval.end){
list.add(intervals.get(n-1));
}else{
list.add(lastInterval);
}
return list;
}