在此函数中,我想找到同一条直线上的最大点数。输入是{[[3,1],[12,3],[3,1],[-6,-1]]}
,得到的输出是3
,正确答案是4
,当我检查这段代码时,发现在map m中有两个元素,它们的关键是相同的,是一对(0.222222, 0.333333)
,为什么?
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
int maxPoints(vector<Point>& points) {
if(points.size()==0) return 0;
int res = 0;
map<pair<double,double>,int> m;
map<int,int> ax;
map<int,int> ay;
for(int i =0;i<points.size();i++){
ay[points[i].y]++;
ax[points[i].x]++;
res = max(max(ay[points[i].y],ax[points[i].x]),res);
auto it = m.begin();
while(it!=m.end()){
//cout << points[i].y << endl;
//cout << it->first.first*points[i].x+it->first.second << endl;
if(points[i].y==it->first.first*points[i].x+it->first.second){
it->second = it->second+1;
res = max(res,it->second);
}
it++;
}
for(int j = i+1;j<points.size();j++){
if(points[i].y==points[j].y||points[i].x==points[j].x) continue;
double k = (points[i].y-points[j].y)*1.0/(points[i].x-points[j].x);
double b = points[i].y - (k*points[i].x);
if(m[make_pair(k,b)]!=0) m[make_pair(k,b)]++;
res = max(m[make_pair(k,b)],res);
}
}
return res;
}