QUESTION:
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]
.
SOLUTION:
和insert Intervals很类似,只是解法依旧TLE,主要是要排序。。。O(N^2)很坑??
/**
* 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> ans=new ArrayList<Interval>();
int n=intervals.size();
//sort?
for(int i=0;i<=n-1;i++)
{
for(int j=i+1;j<=n-1;j++)
if(intervals.get(i).start>intervals.get(j).start)
{
Interval tmp=intervals.get(i);
intervals.set(i,intervals.get(j));
intervals.set(j,tmp);
}
}
//update the interval
for(int i=0;i<=n-2;i++)
{
if(intervals.get(i).end>intervals.get(i+1).start)
{
if(intervals.get(i).end>intervals.get(i+1).end)
{
//eg.[1,5],[2,3]
intervals.set(i+1,new Interval(intervals.get(i).end,intervals.get(i).end));
}
if(intervals.get(i).end<=intervals.get(i+1).end)
{
//eg.[1,5],[2,6]
intervals.set(i,new Interval(intervals.get(i).start,intervals.get(i+1).start));
}
}
}
//here come the res
for(int i=n-1;i>=1;i--)
{
if(intervals.get(i).start==intervals.get(i-1).end)
{
intervals.set(i-1,new Interval(intervals.get(i-1).start, intervals.get(i).end));
intervals.remove(i);
}
}
return intervals;
}
}
so 看discussion
换了个排序方法就好了。。。。。。。
// Sort by ascending starting point using an anonymous Comparator
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval i1, Interval i2) {
return Integer.compare(i1.start, i2.start);
}
});
另一种较快解法
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
int n=intervals.size();
// Sort by ascending starting point using an anonymous Comparator
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval i1, Interval i2) {
return Integer.compare(i1.start, i2.start);
}
});
//Another method
List<Interval> ans=new ArrayList<Interval>();
if(n<=1)
return intervals;
int start=intervals.get(0).start;
int end =intervals.get(0).end;
for(int i=1;i<=n-1;i++)
{
if (intervals.get(i).start <= end) // Overlapping intervals, move the end if needed
{
end=Math.max(end,intervals.get(i).end);
}
else
{
ans.add(new Interval(start, end));
start = intervals.get(i).start;
end = intervals.get(i).end;
}
}
ans.add(new Interval(start, end));
return ans;
}
}