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;
}
唯一注意的是:两种特殊情况。对于重复的点单独计数,对于无斜率的点,单独存到一个单元格里面。