Merge Intervals
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].
Tips:
注意要先按照interval的start排序,要重写compareTo方法。
先把第一个加进去,然后判断下一个interval的开始如果小于前一个的end的话,就不加这次的interval,改result里面的end为当前interval的end和result已存最后一个interval的end的最大值。
Code:
/**
* 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> result = new ArrayList<>();
if (intervals == null || intervals.size() < 2) {
return intervals;
}
Collections.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
for (int i = 0; i < intervals.size(); i++) {
if (result.size() == 0) {
result.add(intervals.get(i));
continue;
}
if (intervals.get(i).start <= result.get(result.size() - 1).end) {
result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, intervals.get(i).end);
} else {
result.add(intervals.get(i));
}
}
return result;
}
}