[leedcode 149] Max Points on a Line

本文介绍了一种算法,用于在二维平面上找到最多共线的点的数量。通过三层遍历,判断点是否位于同一直线上,并记录最大数量。此算法适用于计算机科学领域的几何问题解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
public class Solution {
    public int maxPoints(Point[] points) {
        //三层遍历,依次判断是否这些点在一条线路。注意判断两个相同的点的情况。
        //相同点的个数使用一个计数器dup,非相同但在一条直线上也有一个变量cur
        if(points==null||points.length<=0) return 0;
        int len=points.length;
        int dup=1;
        int cur=1;
        int res=0;
        for(int i=0;i<len;i++){
            dup=1;
            for(int j=i+1;j<len;j++){
                if(points[i].x==points[j].x&&points[i].y==points[j].y){//相同点
                    dup++;
                    continue;
                }
                for(int k=j+1;k<len;k++){
                    if(isSameLine(points[i],points[j],points[k])){
                        cur++;
                    }
                    
                }
                if(res<cur+dup)res=cur+dup;
                cur=1;
            }
            if(res<dup)res=dup;//注意都是相同点的处理
            cur=1;
        }
        return res;
    }
    public boolean isSameLine(Point i,Point j,Point k){//相同点的判断,斜率相同
        if((i.x-j.x)*(i.y-k.y)==(i.x-k.x)*(i.y-j.y)) return true;
        else return false;
        
    }
}

 

转载于:https://www.cnblogs.com/qiaomu/p/4694496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值