LeetCode-Max Points on a Line

博客围绕二维平面上的坐标点问题展开,给定一组二维平面坐标点,要找出能构成一条直线的最多点数。其解法是遍历每个点,统计相同斜率的点数量,找出使点最多的斜率,斜率用分数存储并约分,还给出了Java实现思路。

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

Description:
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

Example 2:

Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6

NOTE:

  • input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

题意:给定一组二维平面上的坐标点,找出能构成一条直线的最多的点,即最多有多少个点可以在同一条直线上;

解法:我们知道一条直线的表达式为y=kx+by=kx+by=kx+b,可以得到直线上的任意两个点满足
x1−x2y1−y2=k \frac{x1-x2}{y1-y2}=k y1y2x1x2=k
因此,遍历坐标上的每个点,统计相同斜率的有多少个点,找出使点最多的那个斜率;为了比较,这里的斜率我们使用分数来存储,并且需要进行约分;

Java
class Solution {
    public int maxPoints(int[][] points) {
        if (points == null) {
            return 0;
        }
        if (points.length <= 2) {
            return points.length;
        }
        
        int result = 0;
        for (int i = 0; i < points.length; i++) {
            int max = 0;
            int overlap = 0;
            Map<String, Integer> map = new HashMap<>();
            for (int j = i + 1; j < points.length; j++) {
                int x = points[j][0] - points[i][0];
                int y = points[j][1] - points[i][1];
                if (x == 0 && y == 0) {
                    overlap++;
                    continue;
                }
                int xyGcd = gcd(x, y);
                x /= xyGcd;
                y /= xyGcd;
                String k = "" + x + y;
                map.put(k, map.getOrDefault(k, 0) + 1);
                max = Math.max(max, map.get(k));
            }
            result = Math.max(result, max + 1 + overlap);
        }
        return result;
    }
    
    public int gcd(int x, int y) {
        if (y == 0) {
            return x;
        }
        return gcd(y, x % y);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值