Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Java:
http://blog.csdn.net/linhuanmars/article/details/21060933
两种方法都和斜率有关
第一种
/**
* 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) {
if(points==null||points.length==0) return 0;
if(allSamePoints(points)) return points.length;
int max=0;
for(int i=0;i<points.length-1;i++)// 前后循环 限制条件一样也能过
{
for(int j=i+1;j<points.length;j++)
{
if(points[i].y==points[j].y&&points[i].x==points[j].x) continue;
int cur=2;
for(int k=0;k<points.length;k++)
{
if(k!=i&&k!=j&&(points[k].y-points[i].y)*(points[j].x-points[i].x)==(points[k].x-points[i].x)*(points[j].y-points[i].y))
cur++;
}
max=Math.max(max,cur);
}
}
return max;
}
private boolean allSamePoints(Point[] points)
{
for(int i=1;i<points.length;i++)
{
if(points[0].y!=points[i].y||points[0].x!=points[i].x) return false;
}
return true;
}
}
第二种
按斜率分类 用hash表
public class Solution {
public int maxPoints(Point[] points) {
if(points==null||points.length==0) return 0;
double ratio=0.0;
int max=1;
for(int i=0;i<points.length-1;i++)
{
HashMap<Double, Integer> map= new HashMap<Double, Integer>();
int numofSame=0;
int localMax=1;
for(int j=i+1;j<points.length;j++)
{
if(points[j].y==points[i].y&&points[j].x==points[i].x)
{
numofSame++;
continue;
}
else if(points[j].x==points[i].x)
{
ratio=(double)Integer.MAX_VALUE;
}
else if(points[j].y==points[i].y)
{
ratio=0.0;
}
else{
ratio=(double)(points[j].y-points[i].y)/(double)(points[j].x-points[i].x);
}
int num=0;
if(map.containsKey(ratio))
{
num=map.get(ratio)+1;
}
else
{
num=2;
}
map.put(ratio,num);
}
for( Integer value:map.values())//values!!!
{
localMax=Math.max(localMax, value);
}
localMax+=numofSame;
max=Math.max(localMax,max);
}
return max;
}
}