LeetCode149-max-points-on-a-line

本文探讨了在二维平面上寻找共线点数最大值的问题,并提供了一种有效的解决方案。通过双层遍历的方式,利用斜率判断共线点的数量,同时考虑到特殊情况的处理,例如点的重复与垂直情况。

问题描述

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
求二维平面上n个点中,最多共线的点数。

Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
|        o
|     o
|  o  
+------------->
0  1  2  3  4
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

解题思路

方法一
  1. 只有0,1,2个点时,分别返回0,1,2
  2. 双层遍历,外层是遍历起点,内层是遍历终点,有以下三层情况:
  3. 若终点跟起点一样或垂直,分别统计重复(chongfu = 0;)/和垂直(chuizhi = 1;)的点数量
  4. 否则就存在斜率,则计算斜率k,统计斜率相同的点数量
  5. 每一个遍历的起点共线最多的点数:max(最多斜率k的点数量, 垂直的点数量) + 重复的点数量

注意:
避免使用double类型来计算斜率的除法,因为double表示的双精度小数在有的系统里不一定准确,为了更加精确无误,我们不做除法,而是把除数和被除数都保存下来分别除以它们的最大公约数,然后放在Map<Map<Integer, Integer>, Integer>里。

public static int maxPoints(Point[] points) {
        if (points.length <= 2) return points.length;
        int max = 0;
        for (int i = 0; i < points.length - 1; i++) {
            Map<Map<Integer, Integer>, Integer> map = new HashMap<>();
            int chongfu = 0;
            int chuizhi = 1;
            for (int j = i + 1; j < points.length; j++) {
                if (points[i].x == points[j].x) {
                    if (points[i].y == points[j].y) {
                        //重复的点
                        chongfu++;
                        continue;
                    } else {
                        //垂直的点
                        chuizhi++;
                        continue;
                    }
                } else {
                    int dy = points[i].y - points[j].y;
                    int dx = points[i].x - points[j].x;
                    int d = gcd(dy, dx);
                    Map<Integer, Integer> m = new HashMap<>();
                    m.put(dx / d, dy / d);
                    map.put(m, map.getOrDefault(m, 1) + 1);
                }
            }
            Integer max_k = 0;
            for (Integer value : map.values()) {
                max_k = Math.max(value, max_k);
            }
            max = Math.max(Math.max(max_k, chuizhi) + chongfu, max);
        }
        return max;
    }

    public static int gcd(int a, int b) {
        return (b == 0) ? a : gcd(b, a % b);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值