题目: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.
这道题需要稍微转变一下思路,用斜率来实现,试想找在同一条直线上的点,怎么判断在一条直线上,唯一的方式也只有斜率可以完成,我开始没想到,后来看网友的思路才想到的,下面是简单的实现:
其中有一点小技巧,利用map<double, int>来存储具有相同斜率值的的点的数量,简洁高效。
/*
Definition for a point
*/
// struct Point {
// int x;
// int y;
// Point():x(0),y(0) {}
// Point (int a, int b):x(0), y(0) {}
// }; int maxPoints(vector<Point> &points) {
if (points.empty())
return ;
if (points.size() <= )
return points.size(); int numPoints = points.size();
map<double, int> pmap; //存储斜率-点数对应值
int numMaxPoints = ; for (int i = ; i != numPoints - ; ++i) {
int numSamePoints = , numVerPoints = ; //针对每个点分别做处理 pmap.clear(); for (int j = i + ; j != numPoints; ++j) {
if(points[i].x != points[j].x) {
double slope = (double)(points[j].y - points[i].y) / (points[j].x - points[i].x);
if (pmap.find(slope) != pmap.end())
++ pmap[slope]; //具有相同斜率值的点数累加
else
pmap[slope] = ;
}
else if (points[i].y == points[j].y)
numSamePoints ++; //重合的点
else
numVerPoints ++; //垂直的点 }
map<double, int>::iterator it = pmap.begin();
for (; it != pmap.end(); ++ it) {
if (it->second > numVerPoints)
numVerPoints = it->second;
}
if (numVerPoints + numSamePoints > numMaxPoints)
numMaxPoints = numVerPoints + numSamePoints;
}
return numMaxPoints + ;
}