給定二維平面上的n個點,找出位於同一直線上的點的最大數目。
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
public class Solution {
public int maxPoints(Point[] points) {
//驗證一下輸入
if (points == null || points.length == 0){
return 0;
}
//一個點或者兩個點直接返回值
if (points.length < 3){
return points.length;
}
int max = 2;
int sameSlopePoint;//相同斜率的點
int samePoint;//相同的點
for (int i = 0; i < points.length; i++){
//初始化一下,剛開始相同點都為零
samePoint = 0;
for(int j = i+1; j < points.length; j++){
sameSlopePoint = 1;//兩點確定一條直線,這個點也應該納入總數
int XDistance = points[j].x - points[i].x;
int YDistance = points[j].y - points[i].y;
if (XDistance == 0 && YDistance ==0){//特殊情況:與第一個點同一位置的點,這時候不用計算后面,因為兩點在同一位置,不能確定一條直線
samePoint++;
}else{
sameSlopePoint = 2;
for(int k = j+1; k < points.length; k++){//找剩下斜率相同的點,三點的斜率相同則肯定在一條直線上
int XDistance2 = points[k].x - points[i].x;
int YDistance2 = points[k].y - points[i].y;
if(XDistance * YDistance2 == XDistance2 * YDistance){//相乘可以避免斜率為零導致除法異常
sameSlopePoint++;
}
}
}
if (max < sameSlopePoint + samePoint){
max = sameSlopePoint + samePoint;
}
}
}
return max;
}
}