题目描述
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
算法分析
暴力枚举法。两点决定一条直线,
n
个点两两组合,可以得到
上面的暴力枚举法以“边”为中心,再看另一种暴力枚举法,以每个“点”为中心,然后遍历剩余点,找到所有的斜率,如果斜率相同,那么一定共线对每个点,用一个哈希表,key为斜率,value为该直线上的点数,计算出哈希表后,取最大值,并更新全局最大值,最后就是结果。时间复杂度 O(n2) ,空间复杂度 O(n) 。
参考程序
1.以“边”为中心
/**
* 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 sz = points.size();
if (sz < 3) return sz;
int res = 0;
for (int i=0; i<sz-1; i++) {
for (int j=i+1; j<sz; j++) {
int cnt = 0, zero = 0;
double a, b, c;
if (points[i].x == points[j].x) {
zero = 1;
} else {
a = points[j].x - points[i].x;
b = points[j].y - points[i].y;
c = a * points[i].y - b * points[i].x;
}
for (int k=0; k<sz; k++) {
if (zero == 0 && a * points[k].y - b * points[k].x == c ||
zero == 1 && points[k].x == points[i].x)
cnt++;
}
res = max(res, cnt);
}
}
return res;
}
};
2.以“点”为中心
class Solution {
public:
int maxPoints(vector<Point>& points) {
int sz = points.size();
if (sz < 3) return sz;
int res = 0;
map<double, int> slopemap;
for (int i=0; i<sz-1; i++) {
slopemap.clear();
int samePoint = 0, cnt = 0, maxp = 1;
double slope;
for (int j=i+1; j<sz; j++) {
if (points[i].x == points[j].x) {
slope = numeric_limits<double>::infinity();
if (points[i].y == points[j].y) {
samePoint++;
continue;
}
} else {
slope = (points[i].y - points[j].y) * 1.0 / (points[i].x - points[j].x);
}
if (slopemap.find(slope) != slopemap.end()) {
cnt = ++slopemap[slope];
} else {
cnt = slopemap[slope] = 2;
}
maxp = max(maxp, cnt);
}
res = max(res, maxp + samePoint);
}
return res;
}
};