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

开始的思路想用k和b两个参数来表示一条直线,这样就需要一个类或者结构体来实现。考虑到应用map容器的自动排序功能,需要写一个重载操作符的函数。于是用一个类来实现。

class Solution;
class lineParameter{
private:
    double k;
    double b;
public:
    lineParameter(double k,double b){
        this->b=b;
        this->k=k;
    }
    void set_value(double k,double b){
        this->b=b;
        this->k=k;
    }
    bool operator <(const lineParameter &s) const//别忘了const
    {
       if(this->k-s.k<-1e-8) return true;
        if(this->k-s.k>1e-8) return false;
        else{
            if(this->b-s.b<1e-8) return true;
            else return false;
        }
    }
    friend class Solution;
};
但是一方面是map容器中引入一个类比较麻烦,另外其实根本不需要两个参数表示一个直线。

对于最多点共线的一条直线,其实对于一个确定的点,只需要根据斜率就可以区分不同的直线。

想麻烦了开始。

最终代码很简单:

int maxPoints(vector<Point>& points) {//共有直线最多1+2+3+,...,+n-1种,直线用pair<k,b>表示
        map<double,int> line;
        double k;
        int max=0;
        int res=1;
        int samepoint=0;
        if(points.size()==0) return 0;
        for(int i=0;i<points.size();i++){
            max=0;
            samepoint=1;
            line.clear();
            for(int j=0;j<points.size();j++){
                if(i==j) continue;
                if((points[i].x==points[j].x&&points[i].y==points[j].y)){
                    samepoint++;
                    continue;
                }
                if((points[i].x-points[j].x!=0)){
                    k=(double)(points[i].y-points[j].y)/(points[i].x-points[j].x);
                    line[k]++;
                }else {
                     line[INT_MAX]++;
                }
            }
            for(map<double,int>::iterator it=line.begin();it!=line.end();it++){
            if(it->second>max) max=it->second;
        }
           if(max+samepoint>res) res=max+samepoint;
        }
        return res;
    }
唯一注意的是:两种特殊情况。对于重复的点单独计数,对于无斜率的点,单独存到一个单元格里面。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值