/**
* 题目:给出一个二维平面上的n个点,求最多有多少个点在同一条直线上。
* 思路:求出直线表达式的三个系数a,b,c,将其余的点代入判断是否在此直线上
* 应该还有更好的算法,暂时没想到
* @author libin
* @version 0.1
*/
public class Test01{
public static void main(String[] args) {
Point point = null;
Point[] points = {
point = new Point(1,2),
point = new Point(3,6),
point = new Point(4,6),
point = new Point(4,8),
point = new Point(0,0),
point = new Point(1,3),
};
System.out.println(maxPionts(points));
}
public static int maxPionts(Point[] points){
if(points == null || points.length == 0){
return 0;
}
int result = 0;
if(points.length == 1){
return 1;
}
//第一层循环确定第一个点
for(int i=0;i<points.length;i++){
//第二层循环确定第二个点,并计算直线系数,此时在同一条直线上的点的个数为2
//j=i+1表示j点为集合中i之后的点(若包含之前的点则会进行重复工作)
for(int j=i+1;j<points.length;j++){
int a = points[j].y - points[i].y;
int b = points[i].x - points[j].x;
int c = a * points[i].x + b * points[i].y;
int num = 2;
//第三层循环确定需要校验的点,用现有的系数进行校验,在同一条直线上则num++
//只校验j点之后的点,避免重复
for(int k=j+1;k<points.length;k++){
if(a*points[k].x + b*points[k].y + c == 0){
num++;
}
}
if(num>result){
result = num;
}
}
}
return result;
}
}
class Point{
int x;
int y;
Point(){
x=0;
y=0;
}
Point(int x,int y){
this.x = x;
this.y = y;
}
}
直线上最多的点的个数
最新推荐文章于 2022-09-07 10:15:03 发布