最多有多少个点在一条直线上
题目
给出二维平面上的n个点,求最多有多少点在同一条直线上。
样例
给出4个点:(1, 2), (3, 6), (0, 0), (1, 3)。
一条直线上的点最多有3个。题解
可以根据任意点跟其他点所构成线段的斜率判断共线的点的个数。通过遍历所有点得到最大值即可。需要注意考虑重复点以及斜率无穷大的情况。
/**
* 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 {
/**
* @param points an array of point
* @return an integer
*/
public int maxPoints(Point[] points) {
if (points == null)
{
return 0;
}
int n = points.length;
if (n <= 1)
{
return n;
}
int max = 0;
double k = 0.0;
for (int i=0;i<n-1;i++)
{
HashMap<Double,Integer> hash = new HashMap<>();
int same = 0;
int localMax = 1;
for (int j=i+1;j<n;j++)
{
if (points[i].x == points[j].x && points[i].y == points[j].y)
{
same++;
continue;
}
else if (points[i].x == points[j].x)
{
k = Double.MAX_VALUE;
}
else if (points[i].y == points[j].y)
{
k = 0.0;
}
else
{
k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
}
int num = hash.containsKey(k)?(hash.get(k).intValue()+1):2;
hash.put(k,num);
}
Set<Double> keySet = hash.keySet();
for (Iterator iterator = keySet.iterator(); iterator.hasNext();)
{
Double key = (Double) iterator.next();
int v = hash.get(key).intValue();
localMax = Math.max(localMax,v);
}
localMax += same;
max = Math.max(max,localMax);
}
return max;
}
}
Last Update 2016.10.27