Q:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
该题我的思路是两层循环,根据斜率来判断属于相同一条直线的点有多少个,如果说是在同一条直线上的那么一般在第一轮就得出这条直线所有的点的数量。除了基本思路之外,还需要考虑一些特殊情况,比如可能会输入一些重复的点,或者两个点组成的直线斜率无法计算等等,这些都要考虑进去。
代码:
class Solution{
public :
int maxPoints(vector<Point> &points){
map<double, int> countMap;
map<double, int>::iterator it;
if(points.empty())return 0;
int sameNum; //可能有重复的点
int maxNum = 1; //所有点中比
int tmpMaxNum = 1; //同一个点所有直线中含有最多的点的个数(同一个点中比)
int numOfLine = 1; //同一条横线上斜率无法表示,只有单独计数
int temp;
for(int i = 0; i < points.size(); i++){
countMap.clear();
sameNum = 0;
numOfLine = 1;
tmpMaxNum = 1;
double xielv;
for(int j = i + 1; j < points.size(); j++){
if(i == 3)
{
xielv = 0;
}
bool flag = false;
if(points[i].x == points[j].x && points[i].y == points[j].y)
{
sameNum++;
continue;
}
if((points[j].x != points[i].x))
xielv = (double)( points[j].y - points[i].y ) / (double)( points[j].x - points[i].x );
else
{
flag = true; //不计算斜率
numOfLine++;
}
it = countMap.find(xielv);
if(!flag) //计算斜率时
{
if(it != countMap.end())
{
temp = ++countMap[xielv];
}
else
{
countMap[xielv] = 2; //该斜率的直线上的点有2个
temp = 2;
}
if(tmpMaxNum < temp)tmpMaxNum = temp;
}
if(tmpMaxNum < numOfLine)tmpMaxNum = numOfLine;
}
if(maxNum < tmpMaxNum + sameNum)
{
maxNum = tmpMaxNum + sameNum;
}
}
return maxNum;
}
};
如果大家有更好的思路,欢迎在评论中提出来,谢谢!