leetcode面试题3: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.

就是算在同一条直线上的点有多少个,需要注意的有几点:

1.坐标相同的点算在同一条直线上

2.斜率相同的点在同一条直线上,但特例是横坐标相同的点斜率不存在

思路是对每个点遍历剩余的点,创建一张哈希表map<double,int>,存储每个斜率对应的直线上的点数,斜率不存在时对应key值INT_MAX

AC代码:

class Solution {
public:
    int maxPoints(vector<Point> &points) {
        double k;
        int i,j,max=0;
        if(points.size()<=2)return points.size();
        for(i=0;i<points.size();i++)
        {
            map<double,int>count;
            count[INT_MIN]=0;
            int samepoint=1;
            for(j=0;j<points.size()&&j!=i;j++)
            {
                if(points[j].x==points[i].x&&points[j].y==points[i].y)
                samepoint++;
                else
                {
                    double k=points[j].x==points[i].x?INT_MAX:(double)(points[j].y-points[i].y)/(double)(points[j].x-points[i].x);
                    count[k]++;
                }
            }
            map<double,int>::iterator ite = count.begin();
            for(ite;ite!=count.end();ite++)
            {
                if(ite->second+samepoint>max)
                max=ite->second+samepoint;
            }
        }
        return max;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值