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]
.
思路: 先对左节点排序,然后遍历整个list, 如果当前右节点等于或者大于下一个interval的左节点,则merge,并更新右节点,直到遇到不满足这种情况的,再选取新的节点,如上,[1,3] , [2,6] 因为 3 > 2, 所以merge, 并更新右节点变为[1,6]。再选下一个[8,10],无法merge,再选下一个。得到结果
/**
* 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() <= 1)
return intervals;
Collections.sort(intervals, new intervalcomparator());
ArrayList<Interval> result = new ArrayList<Interval>();
Interval last = intervals.get(0);
for (int i = 1; i < intervals.size(); i++) {
Interval curt = intervals.get(i);
if (curt.start <= last.end ){
last.end = Math.max(last.end, curt.end);
}else{
result.add(last);
last = curt;
}
}
result.add(last);
return result;
}
private class intervalcomparator implements Comparator<Interval>{
public int compare(Interval a, Interval b){
return a.start - b.start;
}
}
}