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按照 start排序,之后遍历选择就行了。
/**
* 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) {
if (intervals.size() <= 1) {
return intervals;
}
// for (Interval interval : intervals) {
// System.out.println(interval.start);
// }
// 第一部的排序 是非常重要的
// 第一种 lamda表达式 排序,学习了
// sort by ascending starting point using anonymous comparator
// intervals.sort((i1, i2) -> Integer.compare(i1.start, i2.start));
// 一般的思维就是 传入compator比较器啦
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval i1, Interval i2) {
// TODO Auto-generated method stub
if (i1.start > i2.start) {
return 1;
}
else if (i1.start < i2.start) {
return -1;
}
else {
return 0;
}
}
});
// for (Interval interval : intervals) {
// System.out.println(interval.start);
// }
List<Interval> res = new ArrayList<>();
int start = intervals.get(0).start;
int end = intervals.get(0).end;
Iterator iterator = intervals.iterator();
while (iterator.hasNext()) {
Interval temp = (Interval) iterator.next();
// 有重合了
// System.out.println(temp.start);
if (temp.start <= end) {
end = Math.max(end, temp.end);
}
else {
res.add(new Interval(start,end));
start = temp.start;
end = temp.end;
}
}
res.add(new Interval(start, end));
return new ArrayList<>(res);
}
}