leetcode 149. Max Points on a Line

本文探讨了在二维平面上寻找共线点最大数目的算法实现,通过计算不同点之间的斜率来判断是否共线,并使用HashMap存储斜率及对应的点数,巧妙地避免了浮点数运算带来的精度问题。

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

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

Example 1:

Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:

^
|
|        o
|     o
|  o  
+------------->
0  1  2  3  4

给出一系列点的坐标,输出在一条线上最多的点数

思路:
在一条线上说明斜率是一样的,每选中一个点i,看剩下的点(i+1到最后)与它构成的线的斜率,如果斜率一样,这条线上的点数就+1
还有一种情况,就是重复的点,几个点在同一个位置上

同一条线上的点数就是上述两种情况点的和

用一个HashMap保存斜率和这个斜率的次数,每选一个新的点i就要用一个新的HashMap,不然会有重复的case,计算出相同的斜率,这个斜率的次数就+1

斜率,如果直接用两个数除,由于计算机中小数不精确,所以要避免除法,可以用另一个HashMap保存<dx, dy>,或者用一个String保存dx/dy
而且dx和dy要除以它们的最大公约数

因此涉及求最大公约数的问题
gcd(a, b) = return (b == 0) ? a : gcd(b, a%b);
可以证明(a,b)的最大公约数 = (b, a%b)的最大公约数

用HashMap保存斜率的<dx, dy>时间复杂度稍微高一些,所以用String

//13ms
    public int maxPoints(int[][] points) {
        if (points == null) {
            return 0;
        }
        
        if (points.length <= 2) {
            return points.length;
        }
        
        int sameLine = 0;
        int samePoint = 1; 
        int res = 0;
        
        for (int i = 0; i < points.length; i++) {
            HashMap<String, Integer> count = new HashMap<>();
            int[] x = points[i];
            samePoint = 1;
            sameLine = 0;
            
            for (int j = i + 1; j < points.length; j++) {
                int[] y = points[j];
                int dx = x[0] - y[0];
                int dy = x[1] - y[1];
                int d = gcd(dx, dy);
                if (dx == 0 && dy == 0) {  //same points..
                    samePoint ++;
                    continue;
                }
                
                String slope = "" + (dy/d) + "/" + (dx/d);
                count.put(slope, count.getOrDefault(slope, 0) + 1);
                sameLine = Math.max(sameLine, count.get(slope));
                
            }
            
            res = Math.max(res, sameLine + samePoint);
        }
        
        return res;
    }
    
    
    //greatest common divisor..
    public int gcd(int m, int n) {
        return (n == 0) ? m : gcd(n, m % n);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值