您的位置:首页 > 其它

LeetCode:149_Max Points on a line | 寻找一条直线上最多点的数量 | Hard

2014-09-26 18:27 447 查看
题目: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 0;
if (points.size() <= 2)
return points.size();

int numPoints = points.size();
map<double, int> pmap;    //存储斜率-点数对应值
int numMaxPoints = 0;

for (int i = 0; i != numPoints - 1; ++i) {
int numSamePoints = 0, numVerPoints = 0;  //针对每个点分别做处理

pmap.clear();

for (int j = i + 1; 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] = 1;
}
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 + 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: