For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
# 1 based on start 26ms
/**
* 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> res = new ArrayList<Interval>();
if(intervals == null || intervals.size() <= 1) return intervals;
Collections.sort(intervals, new Comparator<Interval>(){
public int compare(Interval a, Interval b){
return a.start - b.start;
}
});
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 {
res.add(new Interval(start, end));
start = interval.start;
end = interval.end;
}
}
res.add(new Interval(start, end));
return res;
}
}
# 2 based on end 24ms
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
List<Interval> res = new ArrayList<Interval>();
if(intervals == null || intervals.size() <= 1) return intervals;
Collections.sort(intervals, new Comparator<Interval>(){
public int compare(Interval a, Interval b){
return b.end - a.end;
}
});
Interval last = intervals.get(0);
Interval cur = null;
for(int i = 1; i < intervals.size(); i++){
cur = intervals.get(i);
if(last.start > cur.end){
res.add(last);
last = cur;
} else {
last.start = Math.min(cur.start, last.start);
}
}
res.add(last);
Collections.reverse(res);
return res;
}
}
# number of meeting rooms, 拆分start,end 20ms
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
int n = intervals.size();
int[] starts = new int[n];
int[] ends = new int[n];
for(int i=0; i<n; i++) {
Interval l = intervals.get(i);
starts[i] = l.start;
ends[i] = l.end;
}
Arrays.sort(starts);
Arrays.sort(ends);
List<Interval> res = new ArrayList<Interval>();
for(int i=0, j=0; i<n; i++) {
if(i == n-1 || starts[i+1] > ends[i]){ // next meeting starts after this ends, cant merge
res.add(new Interval(starts[j], ends[i]));
j = i + 1;
}
}
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。