LeetCode-56 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]
.
/**
* 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) {
if (intervals == null || intervals.size() == 0) {
return intervals;
}
Interval[] intervalArray = intervals.toArray(new Interval[intervals.size()]);
Arrays.sort(intervalArray, new Comparator<Interval>() {//排序
@Override
public int compare(Interval o1, Interval o2) {
return o1.start - o2.start;
}
});
ArrayList<Interval> result = new ArrayList<Interval>();
Interval flag = intervalArray[0];
for (int i = 1; i < intervalArray.length; i++) {//合并的规则判断
if (flag.end < intervalArray[i].start) {
result.add(flag);
flag = intervalArray[i];
} else {
flag.end = Math.max(flag.end, intervalArray[i].end);
}
}
result.add(flag);//不要漏了加上最后一个区间
return result;
}
}
Runtime: 404 ms
分析:这个类型的题目之前有做过,所以看到题目基本知道大概的思路。
但通过new Comparator来设置Arrays.sort方法的排序之前没用过,也算是一收获。
Arrays.sort(intervalArray, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
return o1.start - o2.start;
}
});