给出多个可能重叠的区间,找出重叠区间的个数。

来源:互联网 发布:江民杀毒 知乎 编辑:程序博客网 时间:2024/05/17 05:56
import java.util.Arrays;


class Interval{
int start;
int end;
Interval(int a,int b){
start = a;
end = b;
}
}


class Point implements Comparable<Point>{

int value;
int type;
Point(int v,int t){
value = v;
type = t;
}

public int compareTo(Point p) {
if(this.value == p.value){
return 0;
}else if(this.value > p.value){
return 1;
}else{
return -1;
}
}

}


public class num6 {

public int getOverlappingCount(Interval[] A){
int max = 0,count = 1;
if(A==null || A.length==0) return max;
Point[] points = new Point[A.length*2];
for(int i = 0;i < A.length;i++){
points[2*i] = new Point(A[i].start, 0);
points[2*i+1] = new Point(A[i].end, 1);
}
// Collection.sort(points);
Arrays.sort(points);
for (int i = 0; i < points.length; i++) {
if (points[i].type==0) {
count++;
max = Math.max(max, count);
}else{
count--;
}
}
return max;
}

public static void main(String[] args) {
Interval[] A = new Interval[4];
A[0] = new Interval(1, 5);
A[1] = new Interval(10, 15);
A[2] = new Interval(5, 10);
A[3] = new Interval(20, 30);
int max = new num6().getOverlappingCount(A);
System.out.println(max);
}
}
0 0