Leetcode 149. 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.


解题方法:

从解题方法来看,没有什么特殊的,依次计算每一个点跟其他点的斜率,然后统计数量最多的斜率,这可以在一个哈希表的辅助下完成。但有下面几个细节需要注意:

- 重复点需要统计,不要漏掉了。

- 与y轴平行的是特殊的斜率,需要特别计算。

- 斜率类型是double,计算的时候注意数据的类型,否则是导致计算结果的不准确。


代码:
int maxPoints(vector<Point>& points) {
        int res = 0, n = points.size();
        for(int i = 0; i < n; i++){
            int samePoint = 1;
            unordered_map<double, int> m;
            for (int j = i + 1; j < n;j++){
                if (points[j].x == points[i].x && points[j].y == points[i].y){
                    ++samePoint;
                }else if (points[j].x == points[i].x){
                    m[INT_MAX]++;
                }else{
                    double slope = double(points[j].y - points[i].y)/float(points[j].x - points[i].x);
                    m[slope]++;
                }
            }
            
            int maxCount = 0;
            for(auto pos: m){
                maxCount = max(maxCount, pos.second);
            }
            maxCount += samePoint;
            res = max(res, maxCount);
        }
        return res;
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值