原题链接:https://leetcode.com/problems/merge-intervals/
思路很简单,首先对List进行排序(从小到大),
然后用st 保存当前连续左端最小值 ed保存当前连续右端最大值。
AC 10ms 95% Java:
/**
* 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) {
List<Interval> ans=new ArrayList();
if(intervals==null||intervals.size()==0)
return ans;
Collections.sort(intervals,new Comparator<Interval>(){
public int compare(Interval i1,Interval i2){
if(i1.start==i2.start)
return 0;
return (i1.start>i2.start)?1:-1;
}
});
int st=intervals.get(0).start,ed=intervals.get(0).end;
for(Interval cur:intervals){
if(ed>=cur.start){
ed=Math.max(ed,cur.end);
}else{
ans.add(new Interval(st,ed));
st=cur.start;
ed=cur.end;
}
}
ans.add(new Interval(st,ed));
return ans;
}
}