您的位置:首页 > 其它

max-points-on-a-line

2017-02-22 10:09 155 查看
题目描述
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

IDEA

求出在一条直线上的最大点数。

直线的可能情况:1.在一条垂直x轴的直线上(斜率无穷大),2.斜率相同

CODE

/**
* 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 size=points.size();
if(size==0||size==1)
return size;
int res=1;
for(int i=0;i<size;i++){
map<double,int> m;//m->first斜率 m->second点数
int curmax=1;
int dup=0;//与当前点重合的点数
int vcnt=0;//与当前点在一条垂直线上的,即横坐标相同,
for(int j=0;j<size;j++){
if(j!=i){
double x1=points[i].x-points[j].x;
double y1=points[i].y-points[j].y;
if(x1==0&&y1==0){
dup++;
}else if(x1==0){
if(vcnt==0){
vcnt=2;
}else{
vcnt++;
}
curmax=max(curmax,vcnt);
}else{
double k=y1/x1;
if(m[k]==0){
m[k]=2;
}else{
m[k]++;
}
curmax=max(curmax,m[k]);
}
}
}
res=max(res,curmax+dup);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: