Max Points on a Line--LeetCode

1.题目

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.

2.题意

计算几何,给定一个点集合,求最大的共线点的个数

3.分析

找出相同点和相同斜率的点

通过斜率来判断共线需要用到除法
用double表示的双精度小数在有的系统里不一定准确
为了精确无误的计算,应当避免除法,避免无线不循环小数的出现
可将两数分别除以它们的最大公约数,pair作为key
gcd采用算法导论中的欧几里德算法

注意两个max函数要放在外层循环,不要忘记return res;

4.代码

/**
 * 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 res = 0;

        for(int i = 0; i < points.size(); ++i)
        {
            int duplicate = 1;
            map<pair<int, int>, int> m;
            for(int j = i + 1; j < points.size(); ++j)
            {
                if(points[j].y == points[i].y && points[j].x == points[i].x)
                    ++duplicate;
                else
                {
                    int dy = points[j].y - points[i].y;
                    int dx = points[j].x - points[i].x;
                    int d = gcd(dx, dy);
                    ++m[{dx/d, dy/d}];
                }
            }

            res = max(res, duplicate);
            for(auto it = m.begin(); it != m.end(); ++it)
                res = max(res, it->second + duplicate);
        }

        return res;
    }

private:
    int gcd(int a, int b)
    {
        if(b == 0)
            return a;
        else
            return gcd(b, a % b);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值