算法——计算点集中共线最多点的直线

给定一个二维平面及平面上的 N 个点列表Points,其中第i个点的坐标为Points[i]=[Xi,Yi]。请找出一条直线,其通过的点的数目最多。
设穿过最多点的直线所穿过的全部点编号从小到大排序的列表为S,你仅需返回[S[0],S[1]]作为答案,若有多条直线穿过了相同数量的点,则选择S[0]值较小的直线返回,S[0]相同则选择S[1]值较小的直线返回。
leetcode

解题思路:暴力方法,一次遍历每个可能会产生更多点的直线即可。

  • 怎么求两点是否共线呢?
    分别的求两个点的xy轴的坐标差,在与第三个点的坐标差做比较即可。也就是向量法。
class Solution {
    public int[] bestLine(int[][] points) {
        int[] res = new int[2];
        int num, max = 0, n = points.length;

        for(int i = 0; i < n - 1; i++){
            for(int j = i + 1; j < n; j++) {
                num = 2;
                if(n - j + 1 <= max) break;

                long x1 = points[j][0] - points[i][0];
                long y1 = points[j][1] - points[i][1];

                for(int x = j + 1; x < n; x++) {
                    long x2 = points[x][0] - points[i][0];
                    long y2 = points[x][1] - points[i][1];

                    if(x1 * y2 == x2 * y1) num++;
                }

                if(num > max) {
                    max = num;
                    res[0] = i;
                    res[1] = j;
                }
            }
        }

        return res;
    }
}
原文地址:https://www.cnblogs.com/lippon/p/14117650.html