问题:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:
试想一下,所有跟跟原点的斜率相同的点都在同一条直线上。同理,所有跟某一个固定点斜率相同的点都在同一条直线上。那么我们就用double for loop,其中外层的loop来遍历所有点,每次循环,就找到一个固定点;内层循环从i+1开始,找到所有跟points[i]斜率相同的点(只需要找i右边的即可),然后将count保存在一个map上。需要注意的是,有可能会有相同的点,要注意处理。
代码:(O(n^2))
class Solution {
public:
int maxPoints(vector<Point> &points) {
int result = 0;
map<double, int> counts;
for (int i = 0; i < points.size(); i ++) {
counts.clear();
int same_point = 0;
int curretn_max = 1;
for (int j = i + 1; j < points.size(); j ++) {
double slop = std::numeric_limits<double>::infinity();
if (points[j].x != points[i].x)
slop = 1.0 * (points[j].y - points[i].y) / (points[j].x - points[i].x);
else if (points[j].y == points[i].y) {
same_point ++;
continue;
}
if (counts.find(slop) != counts.end())
counts[slop] ++;
else
counts[slop] = 2;
curretn_max = max(curretn_max, counts[slop]);
}
result = max(result, curretn_max + same_point);
}
return result;
}
};