题目
给定很多线段,每个线段都有两个数[start, end],表示线段开始位置和结束位置,左右都是闭区间,
规定:1. 线段开始和结束的位置一定都是整数值 2. 线段重合区域的长度必须>=1
返回线段最多重合区域中,包含了几条线段
java
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Code_coverMax {
public static void main(String[] args) {
int[][] lines = {
{1,100},{5,99},{2,105},{10,200}, {20,110},{30,202},{15,150}
};
int cover = maxCover1(lines);
int[][] m = {
{1,100},{5,99},{2,105},{10,200}, {20,110},{30,202},{15,150}
};
int cover2 = maxCover2(m);
System.out.println(cover +" "+cover2);
}
public static int maxCover1(int[][] lines){
int min = Integer.MAX_VALUE ;
int max = Integer.MIN_VALUE;
for (int i = 0; i < lines.length; i++) {
min = Math.min(min,lines[i][0]);
max = Math.max(min,lines[i][1]);
}
int cover = 0;
for (double i = min+0.5; i < max; i = i+0.5) {
int cur = 0;
for (int j = 0; j < lines.length; j++) {
if(lines[j][0] < i && lines[j][1] > i){
cur++;
}
}
cover = Math.max(cover,cur);
}
return cover;
}
public static int maxCover2(int[][] m){
Line[] lines = new Line[m.length];
for (int i = 0; i < m.length; i++) {
lines[i] = new Line(m[i][0],m[i][1]);
}
Arrays.sort(lines,new EndComparator());
PriorityQueue<Integer> heap = new PriorityQueue<>(); // 小根堆
int cover = 0;
for (int i = 0; i < lines.length; i++) {
int curStart = lines[i].start;
while (!heap.isEmpty() && curStart>=heap.peek()){
heap.poll();
}
heap.add(lines[i].end);
cover = Math.max(cover,heap.size());
}
return cover;
}
public static class Line{
public int start;
public int end;
public Line(int start, int end){
this.start = start;
this.end = end;
}
}
public static class EndComparator implements Comparator<Line>{
@Override
public int compare(Line o1, Line o2) {
return o1.start - o2.start;
}
}
}