Max Points on a Line

本文介绍了一种算法,用于找出二维平面上的最大共线点数。通过计算每两点间斜率并使用哈希表记录斜率出现次数来找到最多共线点的数目。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.


O(n^2), n次n条直线的便利,每次n条直线遍历都计算当前循环内落点最多的直线是哪条。


--------------

/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int cnt = points.size();
        int samePoint = 0;
        int vertical = 0;
        unordered_map<double, int> slopeMap;
        int ret = 0;
        for (int i = 0; i < cnt; i++) {
            samePoint = 1;
            vertical = 0;
            slopeMap.clear();
            
            int x1 = points[i].x, y1 = points[i].y;
            int maxslope = 0;
            for (int j = 0; j < cnt; j++) {
                if (i == j) continue;
                int x2 = points[j].x;
                int y2 = points[j].y;
                
                if (x1 == x2) {
                    if (y1 == y2) {
                        samePoint++;
                    } else {
                        vertical++;
                    }
                }
                
                double slope = (double)(y2 - y1) / (double)(x2 - x1);
                slopeMap[slope] += 1;
                maxslope = max(maxslope, slopeMap[slope]);
            }
            
            ret = max(ret, max(vertical, maxslope) + samePoint);
        }
        
        return ret;

  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值