您的位置:首页 > 其它

Max Points on a Line

2015-07-31 16:52 239 查看
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

需考虑3类特殊情况:1、x1=x2,斜率无穷大;2、x1=x2,y1=y2,相同点也要计数,当计算最终结果时要加上该值,且相同点个数初始化为1,即其本身;3、y1=y2;

计算斜率时(double)(points[j].y-points[i].y)/(points[j].x-points[i].x)和(double)((points[j].y-points[i].y)/(points[j].x-points[i].x))结果不同,需注意。

/**
* 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) {
int n=points.size();
if(n<3) return n;
int res=0;
map<double,int> mp;
for(int i=0;i<n-1;i++)
{
int samepoint=1;
int maxpoint=0;
int samex=0;

mp.clear();
map<double,int>::iterator it;
for(int j=i+1;j<n;j++)
{
double slope=0.0;
if(i==j)
continue;
if(points[i].x==points[j].x)
{
if(points[i].y==points[j].y)
samepoint++;
else
{
samex++;
maxpoint=max(maxpoint,samex);
}
continue;
}

if(points[i].y==points[j].y)
slope=0.0;
else
slope=(double)(points[j].y-points[i].y)/(points[j].x-points[i].x);
it=mp.find(slope);
if(it!=mp.end())
it->second+=1;
else
mp.insert(pair<double,int>(slope,1));
if(mp[slope]>maxpoint)   //if(it->second>maxpoint)
maxpoint=mp[slope];  //maxpoint=it->second;  结果错误,为6452609,即it=mp.end(),空指针。
}
maxpoint+=samepoint;
res=max(res,maxpoint);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: