Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
/**
* 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 ABx;
int ABy;
int BCx;
int BCy;
if(points.length<=) return points.length;
int max=;//用來記錄最大個數
for(int i=;i<points.length;i++){
int num=;
int temp=;
for(int j=i+;j<points.length;j++){
ABx=points[i].x-points[j].x;
ABy=points[i].y-points[j].y;
if(ABx== && ABy==)//表示出現重複點
{
num++;
}else{
temp++;
for(int k=j+;k<points.length;k++){
BCx=points[j].x-points[k].x;
BCy=points[j].y-points[k].y;
if(ABx*BCy==BCx*ABy){//表示兩個斜率相等,轉化為乘積的形式可以避免分母為0的情況
temp++;
}
}
}
if(max<(num+temp)){
max=num+temp;
}
temp=;
}
}
return max;
}
}