Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路:注意垂直和重叠的点
代码 时间341ms 空间19988k
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
import java.util.*;
public class Solution {
public int maxPoints(Point[] points) {
int n = points.length;
if (n <= 2)
return n;
int res = 0;
for (int i=0;i<n;i++){
HashMap<Float, Integer> a = new HashMap<>();
int vrt = 0;
int dup = 1;
int max = 0;
for (int j=0;j<n;j++){
if (i==j)
continue;
if (points[i].x == points[j].x){
if (points[i].y == points[j].y){
dup++;
}
else {
vrt++;
}
}
else {
float grad = (float)(points[j].y-points[i].y)/(points[j].x-points[i].x);
if (a.get(grad) == null)
a.put(grad, 1);
else {
a.put(grad, a.get(grad) + 1);
}
}
int tmp = vrt;
for (float k:a.keySet())
tmp = Math.max(tmp, a.get(k));
max = tmp + dup;
}
res = Math.max(res, max);
}
return res;
}
}
原文:http://www.cnblogs.com/Melinni/p/7440280.html