LeetCode 3 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.

分析:

 对于每一点,计算和此点在同一直线上的最大点数,然后挑出其中最大的就是结果。

实现注意事项:

1,对于每一点,只需要考虑此点以后的点,因为如果此点和之前的点在同一直线上,则必然在之前的计算中已经考虑在内;

2,Java中0除以整数得+0, 0除以负数得 -0,为了消除这个差异,在结果上要加 0.0;

3,HashMap 用来记录斜率和点数之间的对应关系。

/**
 * 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) {
        if(points==null || points.length==0)
            return 0;
        int max=1;
        //遍历所有点,计算从此点开始经过此点的直线上的最大点数,
        //因为前面的点已经计算过
        for(int i=0; i<points.length; i++){
            max = Math.max(max, maxPoints(points, i));
        }
        return max;
    }
    //此函数计算经过points[start]的所有直线上的最大点数
    public int maxPoints(Point[] points, int start){
        int max = 1;
        int x1 = points[start].x;
        int y1 = points[start].y;
        //dup记录与points[start]重合的点的个数
        int dup = 0;
        //HashMap记录某斜率对应的点数
        HashMap<Double, Integer> map = new HashMap<Double, Integer>();
        for(int i=start+1; i<points.length; i++){
            int x2 = points[i].x;
            int y2 = points[i].y;
            //Java中0除以正数得到+0,0除以负数得到-0,加0.0为了消除两者的区别
            double slope = (x1==x2) ? Double.POSITIVE_INFINITY : (double)(y2-y1)/(double)(x2-x1) + 0.0;
            if(x1==x2 && y1==y2){
                dup++;
                continue;
            }
            int count = 0;
            if(map.containsKey(slope)){
                count = map.get(slope)+1;
            }else{
                count = 2;
            }
            map.put(slope, count);
            max = Math.max(max, count);
        }
        return dup+max;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值