Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
/** * 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) { //三层遍历,依次判断是否这些点在一条线路。注意判断两个相同的点的情况。 //相同点的个数使用一个计数器dup,非相同但在一条直线上也有一个变量cur if(points==null||points.length<=0) return 0; int len=points.length; int dup=1; int cur=1; int res=0; for(int i=0;i<len;i++){ dup=1; for(int j=i+1;j<len;j++){ if(points[i].x==points[j].x&&points[i].y==points[j].y){//相同点 dup++; continue; } for(int k=j+1;k<len;k++){ if(isSameLine(points[i],points[j],points[k])){ cur++; } } if(res<cur+dup)res=cur+dup; cur=1; } if(res<dup)res=dup;//注意都是相同点的处理 cur=1; } return res; } public boolean isSameLine(Point i,Point j,Point k){//相同点的判断,斜率相同 if((i.x-j.x)*(i.y-k.y)==(i.x-k.x)*(i.y-j.y)) return true; else return false; } }