Max Points on a Line

本文介绍了一种使用哈希表的方法来解决给定二维平面上的n个点,找出共线点的最大数量的问题。通过遍历每个点并计算其它点相对于该点的斜率,利用哈希表记录斜率出现的次数,以此确定最多有多少个点位于同一直线上。

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

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


思路:hash表

首先一个方法就是hash内容是斜率和个数

从前往后判断,计算每一个点的斜率,当然需要首先判断是否垂直点,是否同一个点,然后再hash[slope],随时输出最大值,这个只是代表了非同一个点。

还需要加上相同点。接下来还需要和垂直点个数比较。


代码:

/**
 * 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) {
        if(points.empty())  return 0;
        
        int n=points.size();
        int result=0;
        
        for(int i=0;i<n;i++){
            unordered_map<double,int> counter;
            int same=1;
            int ver=1;
            int maxCount=0;
            
            for(int j=i+1;j<n;j++){
                if(points[i].x==points[j].x&&points[i].y==points[j].y){
                    //这个时候是同一个点
                    same++;
                    ver++;
                }else if(points[i].x==points[j].x){
                    ver++;
                }else{
                    double slope=1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x);
                    //这个地方不写1.0*....就是错误啊
                    ++counter[slope];
                    if(counter[slope]>maxCount)   maxCount=counter[slope];
                }
            }
            maxCount+=same;
            if(maxCount<ver)    maxCount=ver;
            if(maxCount>result) result=maxCount;
        }
        
        return result;
    }
};


转载于:https://www.cnblogs.com/jsrgfjz/p/8519866.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值