LeetCode149—Max Points on a Line

本文介绍了一个二维平面上找出最多共线点数量的问题解决方案。通过分析点之间的斜率,该算法能在O(n²)的时间复杂度内找到答案。文章详细解释了如何处理不同情况的点,并给出了具体的实现代码。

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

原题

原题链接

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

Subscribe to see which companies asked this question


分析

O(n2) 复杂度,每个点都要考虑三种情况:

1.普通的点,在同一直线上满足 slope=y1y2x1x2 相等。
2.跟当前点重合的点。
3.跟当前点在同一条直线且平行于y轴的点。

最后最大值可能有两种情况:
1. 与点p重合的点 + 与点p斜率相同
2. 与点p重合的点 + 与点p斜率相同且平行与y轴

返回结果最后+1表示包含点p即可。

代码

class Solution {
private:
    /*计算斜率*/
    double Slope(Point&a ,Point&b)
    {
        return (b.y-a.y)*1.0/(b.x-a.x);
    }

public:
    int maxPoints(vector<Point>& points)
    {
        if(points.size()<2)
            return points.size();
        int res=0;
        for(int i=0;i<points.size();i++)
        {
            int local=0;//局部最优
            int same=0;//与当前点p重合的点
            int infinity=0;//与当前点p平行于Y轴的点
            unordered_map<double,int>count;//与当前点p斜率相同的点

            for(int j=i+1;j<points.size();j++)
            {
                if(points[i].x==points[j].x&&points[i].y==points[j].y)
                {
                    ++same;
                }
                else if(points[i].x==points[j].x)
                {
                    ++infinity;
                }
                else
                {
                    double slope= Slope(points[i],points[j]);

                    count[slope]++;
                }
            }
            int tmp=0;
            for(auto it = count.begin();it!=count.end();it++)
            {
                tmp=max(tmp,it->second);
            }
            local=max(tmp+same,same+infinity);//局部最优
            res=max(local,res);//全局最优
        }
        return res+1;//包含本身
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值