17、消除间隔
merge-intervals: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].
题设要求:给定区间的集合,合并所有重叠的区间。例如,给定区间集合[1,3],[2,6],[8,10],[15,18], 返回[1,6],[8,10],[15,18]。
分析:区间本身是左小右大,在合并时,可以借助数轴来思考。
代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
public class Solution{
public static void main(String[] args)
{
Solution sl = new Solution();
ArrayList<Interval> intervals= new ArrayList<Interval>();
Interval i1=new Interval(1,3);
Interval i2=new Interval(2,6);
Interval i3=new Interval(8,10);
Interval i4=new Interval(15,18);
intervals.add(i1);
intervals.add(i2);
intervals.add(i3);
intervals.add(i4);
ArrayList<Interval> result=(ArrayList<Interval>) sl.merge(intervals);
}
public ArrayList<Interval> merge(ArrayList<Interval> intervals)
{
ArrayList<Interval> res = new ArrayList<>();
if(intervals.size() == 0)
return res;
Collections.sort(intervals, new Comparator<Interval>(){
public int compare(Interval a, Interval b)
{
return a.start - b.start;
}
});;
Interval temp = intervals.get(0);
if(intervals.size() == 1)
{
res.add(temp);
return res;
}
for(int i=1; i<intervals.size(); i++)
{
if(temp.end >= intervals.get(i).start)
{
temp.end = Math.max(temp.end, intervals.get(i).end);
}
else
{
res.add(temp);
temp = intervals.get(i);
}
}
res.add(temp);
return res;
}
}