您的位置:首页 > 其它

[LeetCode] Max Points on a Line

2015-05-25 14:32 411 查看
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

经过同一个点且斜率相等的直线一定是同一条直线,所以我们只要分别计算每一个点与其它点的直线的斜率,统计斜率的个数,找出最大值。可以使用double来表示斜率,使用map<double, int>来统计个数。但是有两点要注意,那就是:

(1) 如果直线与x轴垂直,此时斜率是无穷大,要单独处理

(2) 所给的点中有些是相同的点,此时也要特殊处理一下。

/**
* 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 res = 0, same_cnt, ver_cnt, cnt;
unordered_map<double, int> mp;
double k;
for (int i = 0; i < points.size(); ++i) {
same_cnt = ver_cnt = cnt = 0;
mp.clear();
for (int j = 0; j < points.size(); ++j) {
if (points[i].x == points[j].x) {
if (points[i].y == points[j].y) {
++same_cnt;
continue;
}else {
++ver_cnt;
cnt = max(cnt, ver_cnt);
}
} else {
k = (double) (points[i].y - points[j].y) / (points[i].x - points[j].x);
++mp[k];
cnt = max(cnt, mp[k]);
}
}
res = max(res, cnt + same_cnt);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: