# Max Points on a Line@LeetCode

## Max Points on a Line

1. 对于垂直与`x`轴的直线，采用`Float.POSITIVE_INFINITY`来表示它的斜率。
2. 相同点，用一个变量专门来记录相同点有多少，在内层循环结束之后，加到总计数中。

````java````/**
* 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;
}
}
``````

1.1k 声望
63 粉丝
0 条评论