Max Points on a Line
/**
* 解题思路:
* 1.任找两个点构成直线,求出直线方程的系数 ax-by+c=0;
* 2.求出满足直线方程的点的个数,取最大值。
*
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public int maxPoints(Point[] points) {
int max = 1;
int len = points.length;
if( len<=1 )
return len;
int a, b, c;
int num;
int flag_line = 0;
for( int i=0; i<len; i++ ){
for( int j=i+1; j<len; j++ ){
if( points[i].x==points[j].x && points[i].y==points[j].y ){
continue;
}
flag_line++;
a = points[i].y - points[j].y;
b = points[i].x - points[j].x;
c = points[i].x*points[j].y - points[j].x*points[i].y;
num=0;
for( int k=0; k<len; k++ ){
if( a*points[k].x - b*points[k].y + c ==0 ){
num++;
}
}
if( max<num ){
max = num;
}
}
}
//不存在直线的话,直接返回点的个数
return flag_line==0? len:max;
}
}
/**
* 解题思路:
* 1.任找两个点构成直线,求出直线方程的系数 ax-by+c=0;
* 2.求出满足直线方程的点的个数,取最大值。
*
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public int maxPoints(Point[] points) {
int max = 1;
int len = points.length;
if( len<=1 )
return len;
int a, b, c;
int num;
int flag_line = 0;
for( int i=0; i<len; i++ ){
for( int j=i+1; j<len; j++ ){
if( points[i].x==points[j].x && points[i].y==points[j].y ){
continue;
}
flag_line++;
a = points[i].y - points[j].y;
b = points[i].x - points[j].x;
c = points[i].x*points[j].y - points[j].x*points[i].y;
num=0;
for( int k=0; k<len; k++ ){
if( a*points[k].x - b*points[k].y + c ==0 ){
num++;
}
}
if( max<num ){
max = num;
}
}
}
//不存在直线的话,直接返回点的个数
return flag_line==0? len:max;
}
}