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].
一刷
题解:
使用Comparator来对集合进行sort。 Comparator和Comparable是两个很重要的interface,再加上interable,runnable等,要好好掌握。
Time Complexity O(n), space complexity O(1)
/**
* 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 merge(List intervals) {
List res = new ArrayList<>();
if(intervals == null || intervals.size() == 0)
return res;
Collections.sort(intervals, new InterComparator());
Interval last = intervals.get(0);
for(int i=1; ilast.end){
last.end = curr.end;
}
}
}
res.add(last);
return res;
}
public class InterComparator implements Comparator{
public int compare(Interval a, Interval b){
return a.start - b.start;
}
}
}
也可以不用构造新类
Collections.sort(intervals, new Comparator(){
public int compare(Interval a, Interval b){
return a.start - b.start;
}
});
二刷
题解:
先把list按照起始时间ascending排序,然后通过比较end判断是否要merge
/**
* 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 merge(List intervals) {
List res = new ArrayList<>();
if(intervals == null || intervals.size()<=1) return intervals;
Collections.sort(intervals, new Comparator(){
public int compare(Interval a, Interval b){
return a.start - b.start;
}
});
Interval cur = intervals.get(0);
for(int i=1; i cur.end){
cur.end = intervals.get(i).end;
}
else if(intervals.get(i).start>cur.end){
res.add(cur);
cur = intervals.get(i);
}
}
res.add(cur);
return res;
}
}