平面上同一直线上点的最大数目

给出一个二维的平面,找出位于同一条直线上的点的最大数目

思路:已知两点确定一条直线,那么针对这两个点确定一条直线的斜率,再计算其余的点与该点的斜率,判断斜率是否相同,这样的思路属于暴力破解,需要注意的一点是可能存在点数重叠的情况,这时需要做一下判断。
代码:

/**
 * 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.length == 0 || points.length < 3) {
            return points.length;
        }
        int result = 2;
        for (int i = 0; i < points.length; i++) {
            int samePosition = 0;
            int sameSlope = 1;
            for(int j = i + 1; j < points.length; j++) {
                int dy = (points[j].y - points[i].y);
                int dx = (points[j].x - points[i].x);
                if (dx == 0 && dy == 0) {
                    samePosition++;
                }
                else {
                    sameSlope++;
                    for(int k = j + 1; k < points.length; k++) {
                        int dy1 = (points[k].y - points[i].y);
                        int dx1 = (points[k].x - points[i].x);
                        if(dy1 * dx == dx1 * dy) {
                            sameSlope++;
                        }
                    }
                }
                result = Math.max(result, samePosition + sameSlope);
                sameSlope = 1;
            }
        }
        return result;
    }
    
}

时间复杂度:O(n3),空间复杂度:O(1)

猜你喜欢

转载自blog.csdn.net/w1375834506/article/details/88937333