最多有多少个点在一条直线上
给出二维平面上的n个点,求最多有多少点在同一条直线上。
样例
给出4个点:(1, 2)
, (3, 6)
, (0, 0)
, (1, 3)
。
一条直线上的点最多有3个。
/**
* 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:
/**
* @param points an array of point
* @return an integer
*/
int maxPoints(vector<Point>& points) {
// Write your code here
unordered_map<float, int> slopes;
int maxp = 0, n = points.size();
for (int i = 0; i < n; ++i) {
slopes.clear();
int duplicate = 1;
for (int j = i + 1; j < n; ++j) {
if (points[i].x == points[j].x && points[i].y == points[j].y) {
++duplicate;
continue;
}
float slope = (points[i].x == points[j].x) ? INT_MAX : (float)(points[i].y - points[j].y) / (points[i].x - points[j].x);
++slopes[slope];
}
maxp = max(maxp, duplicate); //当全部点都为同一个点时,slopes这个map为空,因此需要这一句
for (auto slope : slopes) {
if (slope.second + duplicate > maxp)
maxp = slope.second + duplicate;
}
}
return maxp;
}
};