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 个点两两组合,可以得到12n(n+1)条直线,对每一条直线,判断 n 个点是否在该直线上,从而可以得到这条直线上的点的个数,选择最大的那条直线返回。复杂度O(n3)

上面的暴力枚举法以“边”为中心,再看另一种暴力枚举法,以每个“点”为中心,然后遍历剩余点,找到所有的斜率,如果斜率相同,那么一定共线对每个点,用一个哈希表,key为斜率,value为该直线上的点数,计算出哈希表后,取最大值,并更新全局最大值,最后就是结果。时间复杂度 O(n2) ,空间复杂度 O(n)

参考程序

1.以“边”为中心

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    int maxPoints(vector<Point>& points) {
        int sz = points.size();
        if (sz < 3) return sz;

        int res = 0;
        for (int i=0; i<sz-1; i++) {
            for (int j=i+1; j<sz; j++) {
                int cnt = 0, zero = 0;
                double a, b, c;
                if (points[i].x == points[j].x) {
                    zero = 1;
                } else {
                    a = points[j].x - points[i].x;
                    b = points[j].y - points[i].y;
                    c = a * points[i].y - b * points[i].x;
                }
                for (int k=0; k<sz; k++) {
                    if (zero == 0 && a * points[k].y - b * points[k].x == c ||
                        zero == 1 && points[k].x == points[i].x)
                        cnt++;
                }
                res = max(res, cnt);
            }
        }
        return res;
    }
};

2.以“点”为中心

class Solution {
public:
    int maxPoints(vector<Point>& points) {
        int sz = points.size();
        if (sz < 3) return sz;

        int res = 0;
        map<double, int> slopemap;
        for (int i=0; i<sz-1; i++) {
            slopemap.clear();
            int samePoint = 0, cnt = 0, maxp = 1;
            double slope;
            for (int j=i+1; j<sz; j++) {
                if (points[i].x == points[j].x) {
                    slope = numeric_limits<double>::infinity();
                    if (points[i].y == points[j].y) {
                        samePoint++;
                        continue;
                    }
                } else {
                    slope = (points[i].y - points[j].y) * 1.0 / (points[i].x - points[j].x);
                }
                if (slopemap.find(slope) != slopemap.end()) {
                    cnt = ++slopemap[slope];
                } else {
                    cnt = slopemap[slope] = 2;
                }
                maxp = max(maxp, cnt);
            }
            res = max(res, maxp + samePoint);
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值