Leetcode 149 Max Points on a Line
对于点来说,分三种情况:
1.普通点:具有斜率。
2.垂直于X轴的点:斜率无穷大。
3.坐标相同的点。
我们将1和2分别进行讨论,然后和3的个数分别相加,求出较大者,即为对于一个点来说,和它共线的最多的点的个数。
再通过循环得出最大值即可。
class Solution { public: double getGradient(Point p1, Point p2) { return (double)(p2.y - p1.y) / (p2.x - p1.x); } int maxPoints(vector<Point>& points) { int n = points.size(); if (n <= 1) { return n; } int res = 0; for (int i=0; i<points.size(); ++i) { int localmax = 1; int samePoints = 0; int sameX = 0; int sameGradient = 1; unordered_map<double, int> hashmap; for(int j=0; j<points.size() && i != j; ++j){ if (points[i].x == points[j].x && points[i].y == points[j].y) { ++samePoints; continue; } if (points[i].x == points[j].x) { if (sameX == 0) { sameX = 2; } else { ++sameX; } } else { double gradient = getGradient(points[i], points[j]); if (hashmap[gradient] == 0) { hashmap[gradient] = 2; } else { ++hashmap[gradient]; } } } for(unordered_map<double, int>::iterator it = hashmap.begin(); it!=hashmap.end(); ++it) { sameGradient = max(sameGradient, it->second); } localmax = max(sameGradient + samePoints, sameX + samePoints); res = max(res, localmax); } return res; } };