这道题其实本身并不难。几种情况分类讨论有点乱。
没写出来,看了别人的答案:
/**
* 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<Interval> merge(List<Interval> intervals) {
List<Interval> ans = new ArrayList<>();
if (intervals == null || intervals.size()==0) return ans;
ans.add(intervals.get(0));
for (int i=1; i<intervals.size(); i++) {
Interval curr = intervals.get(i);
int j = ans.size()-1;
for (; j>=0; j--) {
Interval prev = ans.get(j);
if (prev.end < curr.start) {
ans.add(j+1, curr);
break;
}
else if (prev.start <= curr.start) {
prev.end = Math.max(prev.end, curr.end);
break;
}
else if (prev.start <= curr.end) {
prev.start = curr.start;
prev.end = Math.max(prev.end, curr.end);
curr = prev;
ans.remove(j);
}
else {
continue;
}
}
if (j<0) ans.add(0,curr);
}
return ans;
}
}