题目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line
给定二维平面上的n个点,求出位于同一直线上的点的最大个数
思路:
相同的点算多个,这一点也是醉了
斜率无限大情况和相同点的情况要考虑到
还有map中的key,-0和+0算两个key
以及浮点数的精度问题
暂定这样,以后会回来修改,思路有,实现起来太恶心,还有牛客的测试用例和leetcode不一样
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
public class Solution {
public int maxPoints(Point[] points) {
int length = points.length;
if (length == 0 || length == 1 || length == 2)
return length;
float gradients[][] = new float[length][length];
Map<Float, Integer> map[] = new Map[length];
int sames[] = new int[length];
for (int i = 0; i < length; ++i) {
float tmp;
map[i] = new HashMap<Float, Integer>();
for (int j = 0; j <= i; ++j) {
if (j == i)
gradients[i][j] = tmp = Float.MAX_VALUE; // 代表两个点相同
else {
if (points[i].x == points[j].x) {
if (points[i].y == points[j].y) {
sames[i]++; // 代表点i前面i-1个点中有多少个相同的点
gradients[i][j] = tmp = Float.MAX_VALUE;
} else
gradients[i][j] = tmp = Float.MIN_VALUE; // 代表斜率为无穷
} else
gradients[i][j] = tmp = (float) (points[i].x - points[j].x)
/ (float) (points[i].y - points[j].y);
}
if (tmp != Float.MAX_VALUE) {
Integer t = map[i].get(tmp);
if (t == null)
t = 0;
map[i].put(tmp, t + 1);
}
}
}
int bigest = 0;
for (int i = 0; i < length; ++i) {
int same = sames[i];
if (same > bigest) {
bigest = same;
}
for (int m : map[i].values()) {
if (m == Float.MAX_VALUE)
continue;
int tmp = m + same;
if (tmp > bigest)
bigest = tmp;
}
}
return bigest + 1; // 别忘了把此点本身加上
}
}
网友评论