题目描述: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].
思路:根据区间的起始项先进行排序,然后两两比较,合并区间。
代码:
import java.util.*;
/**
* 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 {
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
if(intervals == null || intervals.size() < 2){
return intervals;
}
Collections.sort(intervals, new Comparator<Interval>(){
@Override
public int compare(Interval o1, Interval o2){
return o1.start - o2.start;
}
});
for(int i = 1; i < intervals.size(); i++){
int preStart = intervals.get(i - 1).start;
int preEnd = intervals.get(i - 1).end;
int curStart = intervals.get(i).start;
int curEnd = intervals.get(i).end;
if(curStart <= preEnd){
intervals.set(i, new Interval(preStart, Math.max(preEnd, curEnd)));
intervals.set(i - 1, null);
}
}
while(intervals.remove(null));
return intervals;
}
}