直线上最多的点的个数

/**
 * 题目:给出一个二维平面上的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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值