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) {}
* };
*/
bool visit[10000];
class Solution {
public:
int maxPoints(vector<Point> &points) {
int i,j;
int len = points.size();
double a,b,c;
int count;
int minCount = 0;
if(points.size()<3)
{
return points.size();
}
for(i=0;i<10000;i++)
{
visit[i] = false;
}
for(i=0;i<len-1;i++)
{
visit[i] = true;
for(j=i+1;j<len;j++)
{
visit[j] = true;
if(points[i].x==points[j].x)
{
a = 1;
b = 0;
c = -points[i].x;
}else if(points[i].y == points[j].y)
{
a = 0;
b = 1;
c = -points[i].y;
}else
{
a = -(points[i].y-points[j].y)/(double)(points[i].x-points[j].x);
b = 1;
c = (points[i].y*points[j].x-points[i].x*points[j].y)/(double)(points[i].x-points[j].x);
}
count = getNum(a,b,c,len,points);
if(count>minCount)
{
minCount = count;
}
visit[j] = false;
}
visit[i] = false;
}
return minCount +2;
}
int getNum(double a, double b, double c,int len,vector<Point> &points)
{
int i;
double res;
double min = 0.000001;
int count = 0;
for(i=0;i<len;i++)
{
if(!visit[i])
{
res = a*points[i].x+b*points[i].y+c;
if(((res-0)<min)&&((res-0)>-min))
{
count++;
}
}
}
return count;
}
};
参照网上的方法,我稍作修改。
http://blog.csdn.net/doc_sgl/article/details/17103427
1.使用双重循环,在第二重循环把斜率用map存起来,这样降低了时间复杂度。
2.要注意重复的情况,重复是指和第一个点相同,重复的次数加上斜率出现的次数,就是这条线上总的点的个数。
3.原文使用map[INT_MIN]来处理无法确定直线的情况,而从理论上来讲,进了第一层循环,就至少为1.进了第二重循环,就至少为2.而duplicates很多时,也需要更改max.
/**
* 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 i=0,j=0,l=0,len = points.size();
int max = 0,count = 0;
double k = 0,tmp;
map<double,int> pointMap;
int dup = 0;
for(i=0;i<len;i++)
{
pointMap.clear();
if(max<1)
max = 1;
//设置dup为1,然后每多一个斜率,其值加上这个dup
dup = 1;
for(j=0;j<len;j++)
{
if(i==j)
{
continue;
}
if(max<2)
max = 2;
if(points[j].x==points[i].x && points[j].y==points[i].y)
{
dup++;
continue;
}
if(points[j].x==points[i].x)
{
pointMap[999999999.0]++;
}else
{
k = (double)(points[j].y-points[i].y)/(points[j].x-points[i].x);
pointMap[k]++;
}
}
for(map<double,int>::iterator it = pointMap.begin();it!=pointMap.end();it++)
{
if(it->second+dup>max)
{
max = it->second+dup;
}
}
if(max<dup)
max = dup;
}
return max;
}
};