Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
知道思路:先对每个节点求出其他节点到此节点的斜率,在排序,找最长相同斜率的个数,但是尴尬的是竟然写了一个多小时,也是醉了
import java.util.Arrays;
public class Solution {
public int maxPoints(Point[] points) {
if(points == null || points.length == 0) return 0;
if(points.length == 1) return 1;
double[] slops = new double[points.length-1];
int max = 2;
for(Point start : points) {
int cnt = 0, same = 0;
for(Point end : points) {
if(start.x == end.x && start.y == end.y) same ++;
else if(start.x == end.x) slops[cnt++] = Integer.MAX_VALUE;
else slops[cnt++] = (end.y - start.y + 0.0) / (end.x - start.x);
}
Arrays.sort(slops, 0, cnt);
if(same == points.length) return points.length;
for(int i=0; i<cnt-1; i++) {
int count = 1 + same;
while(i<cnt-1 && slops[i] == slops[i+1]) {
count++;
i++;
}
if(count > max) {
max = count;
}
}
}
return max;
}
}