原题:
解题方法:
代码:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
解题方法:
从解题方法来看,没有什么特殊的,依次计算每一个点跟其他点的斜率,然后统计数量最多的斜率,这可以在一个哈希表的辅助下完成。但有下面几个细节需要注意:
- 重复点需要统计,不要漏掉了。
- 与y轴平行的是特殊的斜率,需要特别计算。
- 斜率类型是double,计算的时候注意数据的类型,否则是导致计算结果的不准确。
代码:
int maxPoints(vector<Point>& points) {
int res = 0, n = points.size();
for(int i = 0; i < n; i++){
int samePoint = 1;
unordered_map<double, int> m;
for (int j = i + 1; j < n;j++){
if (points[j].x == points[i].x && points[j].y == points[i].y){
++samePoint;
}else if (points[j].x == points[i].x){
m[INT_MAX]++;
}else{
double slope = double(points[j].y - points[i].y)/float(points[j].x - points[i].x);
m[slope]++;
}
}
int maxCount = 0;
for(auto pos: m){
maxCount = max(maxCount, pos.second);
}
maxCount += samePoint;
res = max(res, maxCount);
}
return res;
}