Max Points on a Line(Hard)
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
任意一条直线都可以表述为
y = ax + b
假设,有两个点(x1,y1), (x2,y2),如果他们都在这条直线上则有
y1 = kx1 +b
y2 = kx2 +b
由此可以得到关系,k = (y2-y1)/(x2-x1)。即如果点c和点a的斜率为k, 而点b和点a的斜率也为k,可以知道点c和点b也在一条线上。
取定一个点points[i], 遍历其他所有节点, 然后统计斜率相同的点数,并求取最大值即可
/**
* 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 length = points.length;
if (length < 3)
return length;
int max = 2;
for (int i = 0; i < length; i++) {
int pointMax = 1, samePointCount = 0;
HashMap<Double, Integer> slopeCount = new HashMap<Double, Integer>();
Point origin = points[i];
for (int j = i + 1; j < length; j++) {
Point target = points[j];
if (origin.x == target.x && origin.y == target.y) {
samePointCount++;
continue;
}
double k;
if (origin.x == target.x) {
k = Float.POSITIVE_INFINITY;
} else if (origin.y == target.y) {
k = 0;
} else {
k = ((float) (origin.y -target.y)) / (origin.x - target.x);
}
if (slopeCount.containsKey(k)) {
slopeCount.put(k, slopeCount.get(k) + 1);
} else {
slopeCount.put(k, 2);
}
pointMax = Math.max(pointMax, slopeCount.get(k));
}
pointMax += samePointCount;
max = Math.max(pointMax, max);
}
return max;
}
}