Ref : http://fisherlei.blogspot.com/2013/04/leetcode-merge-intervals-solution.html
复用一下Insert Intervals的解法即可。 大家可以看到在此算法中,完整使用了Insert Interval的代码。
http://blog.youkuaiyun.com/imabluefish/article/details/38701089
创建一个新的interval集合,然后每次从旧的里面取一个interval出来,然后插入到新的集合中。
/**
* 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 List merge(List intervals) {
ArrayList ret = new ArrayList();
if (intervals == null) {
return null;
}
for (Interval newInterval: intervals) {
ret = insert(ret, newInterval);
}
return ret;
}
public ArrayList insert(List intervals, Interval newInterval) {
ArrayList ret = new ArrayList();
if (intervals == null) {
return null;
}
Interval last = newInterval;
for (int i = 0; i < intervals.size(); i++) {
Interval curr = intervals.get(i);
// if curr is on the left of last.
if (curr.end < last.start) {
ret.add(curr);
// if curr is on the right of last.
} else if (curr.start > last.end) {
ret.add(last);
last = curr;
} else {
last.start = Math.min(last.start, curr.start);
last.end = Math.max(last.end, curr.end);
}
}
ret.add(last);
return ret;
}
}