每个查询返还该点被多少线段覆盖了
import java.util.ArrayList;
public class n个线段m个查询 {
public static class Line{
private int start;
private int end ;
public Line(int start , int end){
this.start = start ;
this.end = end;
}
public int getStart(){
return start ;
}
public int getEnd(){
return end;
}
}
public static void insert(ArrayList<Line> lines ,int start , int end){
int i= 0;
for(Line line_t : lines){
if(start < line_t.getStart()){
lines.add(i , new Line(start,end));
return;
}
i++;
}
lines.add(new Line(start,end));
}
public static int chaxun(ArrayList<Line> lines , int dian){
int count = 0;
//不能二分查找,就从头开始遍历
for(Line line_t: lines){
if(line_t.getStart() > dian) return count;
if(line_t.getEnd() >= dian){
count++;
}
}
return count;
}
public static void main(String[] args) {
ArrayList<Line> lines = new ArrayList<Line>();
insert(lines,1,10);
insert(lines, 3, 5);
insert(lines, 7, 8);
int res = chaxun(lines , 4);
System.out.println(res);
insert(lines,3,8);
res = chaxun(lines , 4);
System.out.println(res);
}
}
另一种方法:道理是一样的
public class n个线段m个查询 {
public static int count = 0;
public static void insert(int [] start , int [] end , int [] paixu_start ,int start_dian , int end_dian){
start[count] = start_dian;
end[count] = end_dian;
int i = count;
for(i = count ;i>0 ;i--){
if(start[count-1]>start_dian){
paixu_start[i] = paixu_start[i-1];
}else break;
}
paixu_start[i] = count;
count++;//下一个要插入的下标
}
public static int chaxun(int[] start , int [] end , int [] paixu_start , int dian){
int sum = 0;
for(int i = 0 ; i<count;i++){
if(start[paixu_start[i]]>dian) return sum;
if(end[paixu_start[i]]>=dian) sum++;
}
return sum;
}
public static void main(String[] args) {
int n = 6;
int m = 4;
int [] start = new int[n];
int [] end = new int[n];
int [] paixu_start = new int[n];
insert(start , end , paixu_start,1,10);
insert(start , end , paixu_start, 3, 5);
insert(start , end , paixu_start, 7, 8);
int res = chaxun(start , end , paixu_start , 4);
System.out.println(res);
insert(start , end , paixu_start,3,8);
res = chaxun(start , end , paixu_start , 4);
System.out.println(res);
}
}