/*为了确定在一条直线上的点,可以采用斜率进行统计。
对于每个点i,遍历其他所有点,求这些点与i组成的直线的斜率,
斜率相同的点都在一条直线,统计每条直线上点的数目,并获得
他们的最大值。最后取在所有遍历点后,返回这些最大值中最大的数。
方法参考自:https://github.com/soulmachine/leetcode*/
//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() < 3) return points.size();
int res(0);
map<double, int> slope_count;
for(int i = 0; i < points.size(); ++i){
slope_count.clear();
int samePoint_num(0);
int point_max(1);//记录经过i的直线,且落在该直线上点最多的数目
double slope;
for(int j = i+1; j < points.size(); ++j){
if(points[i].x == points[j].x){
if(points[i].y == points[j].y){//与points[i]点是同一点
++samePoint_num;
continue;
}
else{
slope = std::numeric_limits<double>::infinity();
}
}
else{
slope = 1.0*(points[i].y - points[j].y) / (points[i].x - points[j].x);
}
int count(0);
if(slope_count.find(slope) != slope_count.end()){
count = ++slope_count[slope];
}
else{
count = 2;
slope_count[slope] = 2;
}
point_max = point_max>count ? point_max : count;
}
res = res>point_max+samePoint_num ? res : point_max+samePoint_num;
}
return res;
}
};
LeetCode之Max Points on a Line
最新推荐文章于 2021-06-24 01:03:29 发布