Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
先上代码
/**
* 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) {
if (points.size() == 0)
return 0;
if (points.size() == 1)
return 1;
int result = 0;
double k;
for (int i = 0;i < points.size();i++){
map<double,int> kMap;
int reCount = 0;//重复的点
int vCount = 1;//竖直的计数
int currentMax = 1;//当前最大值存储
for (int j = i+1;j < points.size();j++){
if (points[i].x == points[j].x && points[i].y == points[j].y){
reCount++;
}else{
if (points[i].x == points[j].x){
vCount++;
currentMax = max(currentMax,vCount);
}else{
k = 1.0 * (points[j].y-points[i].y) / (points[j].x-points[i].x);
if (kMap[k] == 0)
kMap[k] = 2;
else
kMap[k]++;
}
}
currentMax = max(kMap[k],currentMax);
}
result = max(result,currentMax+reCount);
}
return result;
}
};
按照给出的提示,本题采用的是穷举的思路。
将所有的情况列举出来,这条占点最多的线自然就求出来了。
1、首先,我们将0个点和1个点的情况筛选出来
2、考虑共线的条件:{
斜率相等
竖直
两点相同
}
3、循环走起😄