还是出了点小bug, 没有一开始就反应过来处理intervals == null这些edge cases, 二是没有一开始立刻排序,三是end = Math.max(end,interval.end);
这里一开始直接写的end = interval.end;
/**
* 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; }
* }
*/
class Solution {
public List<Interval> merge(List<Interval> intervals) {
List<Interval> res = new ArrayList<>();
if (intervals == null || intervals.size() == 0){
return res;
}
Collections.sort(intervals, sortByStart);
int start = intervals.get(0).start;
int end = intervals.get(0).end;
for (Interval interval : intervals){
if (interval.start <= end){
end = Math.max(end,interval.end);
} else {
Interval newInterval = new Interval(start, end);
res.add(newInterval);
start = interval.start;
end = interval.end;
}
}
res.add(new Interval(start, end));
return res;
}
private Comparator<Interval> sortByStart = new Comparator<Interval>(){
public int compare(Interval i1, Interval i2){
return i1.start - i2.start;
}
};
}