Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
这道题考虑用如下表达式表达直线:
point:(a0,b0), (a1,b1),
line:(a1-a0)y+(b0-b1)x+(a0b1-a1b0)=0
麻烦在于:相同点的处理:
先找一个点i,
再找一个点j,如果i,j相同,则same++,表示当前重复的点
如果i,j不同,则可确定一条直线,后面的点k带入方程,满足条件tmp++
最后的一条直线的点的个数就是same+tmp
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
//point:(a0,b0), (a1,b1),
//line:(a1-a0)y+(b0-b1)x+(a0b1-a1b0)=0
public class Solution {
public int maxPoints(Point[] points) {
int i,j,k;
int n=points.length;
if(n<3)
return n;
int a,b,c;
int tmp,max=2;
int same;
for(i=0;i<n;i++)
{
same=0;
tmp=1;
for(j=i+1;j<n;j++)
{
a=(points[j].x-points[i].x);
b=(points[i].y-points[j].y);
if(a==0 && b==0)
{
tmp++;
same++;
//all same point
if(j==n-1 && tmp>max)
max=tmp;
continue;
}
else
{
c=(points[i].x*points[j].y-points[j].x*points[i].y);
tmp++;
for(k=j+1;k<n;k++)
{
if((a*points[k].y+b*points[k].x+c)==0)
tmp++;
}
if(tmp>max)
max=tmp;
tmp=same+1;
}
}
}
return max;
}
}