您的位置:首页 > 其它

[leetcode] Max Points on a Line

2014-08-14 00:07 316 查看
Max Points on a
Line

以点为中心暴力枚举。斜率相同点共线。

注意:重合点,与y轴平行。

/**
* 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()<3){
return points.size();
}
int res=0;
unordered_map<double,int> slope_cnt;//斜率计数
for(int i=0;i<points.size()-1;i++){
slope_cnt.clear();
int samePointNum=0;//与i重合的点
int point_max=1;//与i共线的最大点数

for(int j=i+1;j<points.size();j++){
double slope;//斜率
if(points[i].x==points[j].x){
if(points[i].y==points[j].y){//点重合
++samePointNum;
continue;
}else{
slope=std::numeric_limits<double>::infinity();//平行Y轴,斜率无穷大
}
}else{
slope=1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x);
}
int cnt=0;
if(slope_cnt.find(slope)!=slope_cnt.end()){//已有记录
cnt=++slope_cnt[slope];
}else{
cnt=2;
slope_cnt[slope]=cnt;
}
if(point_max<cnt){//更新point_max
point_max=cnt;
}
}
res=max(res,point_max+samePointNum);//
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: