Given a collection of intervals, merge all overlapping intervals.
- Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. - Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
解法
先将其按start的大小从小到大排序,再遍历,如果当前interval的start小于或等于res里面最后一个interval的end,则把他们两个合并,如果大于则将当前interval添加到res中
public List<Interval> merge(List<Interval> intervals) {
List<Interval> res=new ArrayList<Interval>();
if(intervals==null||intervals.size()==0)
return res;
intervals.sort(new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
// TODO Auto-generated method stub
return o1.start-o2.start;
}
});
int n=intervals.size();
Interval I=intervals.get(0);
res.add(intervals.get(0));
for(int i=1;i<n;i++)
{
if(res.get(res.size()-1).end>=intervals.get(i).start)
res.get(res.size()-1).end=Math.max(intervals.get(i).end,res.get(res.size()-1).end);
else
res.add(intervals.get(i));
}
return res;
}
Runtime: 12 ms, faster than 84.87% of Java online submissions for Merge Intervals.
Memory Usage: 46 MB, less than 5.76% of Java online submissions for Merge Intervals.
解法二
把start和end分别保存在数组中再从小到大排序,然后遍历数组,如果starts[i+1]>ends[i]则说明不连续了,要把之前的加入数组当中
public List<Interval> merge(List<Interval> intervals) {
List<Interval> res=new ArrayList<Interval>();
if(intervals==null||intervals.size()==0)
return res;
int n=intervals.size();
int[] starts=new int[n];
int[] ends=new int[n];
int i=0;
for(Interval I:intervals)
{
starts[i]=I.start;
ends[i++]=I.end;
}
Arrays.sort(starts);
Arrays.sort(ends);
int j=0;
for(i=0;i<n;i++)
{
if(i==n-1||starts[i+1]>ends[i])
{
res.add(new Interval(starts[j],ends[i]));
j=i+1;
}
}
return res;
}
Runtime: 7 ms, faster than 99.68% of Java online submissions for Merge Intervals.
Memory Usage: 44.8 MB, less than 38.20% of Java online submissions for Merge Intervals.