合并区间 给定一个区间集合,合并里面重叠的区间,并返回新的不含重叠区间的集合。public class num8 { public ArrayList merge(ArrayLi

public class num8 {
public ArrayList merge(ArrayList intervals){
ArrayList res = new ArrayList();
if(intervals == null || intervals.isEmpty()) return res;
Comparator comparator = new Comparator() {
@Override
public int compare(Interval a, Interval b) {
if(a.start < b.start) return -1;
else if(a.start > b.start) return 1;
else{
if(a.end < b.end) return -1;
else if(a.end > b.end) return 1;
else return 0;
}
}
};
Collections.sort(intervals, comparator);
/*
System.out.println("zcf");
for (Interval interval : intervals) {
System.out.println(interval.start + "," + interval.end);
}*/

for(int i = 0 ;i < intervals.size();i++){
Interval current = intervals.get(i);
if(res.isEmpty()){
res.add(current);
}else {
Interval last = res.get(res.size() - 1);
if(last.end >= current.start){
last.end = Math.max(last.end, current.end);
}else{
res.add(current);
}
}
}
return res;
}
public static void main(String[] args) {
Interval[] A = new Interval[4];
A[0] = new Interval(1, 5);
A[1] = new Interval(6, 10);
A[2] = new Interval(4, 6);
A[3] = new Interval(15, 20);
ArrayList aIntervals = new ArrayList();
for(int i = 0;i < A.length;i++){
aIntervals.add(A[i]);
}
ArrayList res = new ArrayList();
res = new num8().merge(aIntervals);
System.out.println(res.size());
for (Interval interval : res) {
System.out.println(interval.start + "," + interval.end);
}
}
}

你可能感兴趣的:(进军硅谷——java)