已知在二维平面上有一堆点,用穷举法求同一条直线上点最多的个数
/**
* 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) {
if (points == null) {
return 0;
}
int length = points.length;
if (length <= 2)
return length;
int max = 2;
for (int i = 0; i < length; i++) {
int num0 = 0;// 记录重复点的个数
int num1 = 1;// 记录同一条线上的点
for (int j = i + 1; j < length; j++) {
int x1 = points[i].x - points[j].x;
int y1 = points[i].y - points[j].y;
if (x1 == 0 && y1 == 0) {// 重复点
num0++;
} else {
// 两点肯定组成一条线 i,j
num1++;
// 判断第三个点是否在这条直线上
for (int k = j + 1; k < length; k++) {
int x2 = points[j].x - points[k].x;
int y2 = points[j].y - points[k].y;
if (x1 * y2 == x2 * y1) {// 第三个点在直线上
num1++;
}
}
}
if (max < (num0 + num1))
max = num0 + num1;
num1 = 1;// j++ ,另一条直线 重置 num1=1
}
}
return max;
}
}