LeetCode--149.Max Points on a Line(一条线上最多有几个点)
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Point数据结构
class Point { int x; int y; Point() { x = 0; y = 0; } Point(int a, int b) { x = a; y = b; } }
方法:选定一个点分别和其他点求斜率,如果斜率相同则在一条直线上,记录下数量,不同的斜率的数量使用HashMap进行保存。然后再选择另一个点进行相同的操作。
注意:斜率为0,点重合的情况
public static int maxPoints(Point[] points) { int len = points.length; if(len<=2) return len; int maxnum = 0; HashMap<Double,Integer> map = new HashMap<Double,Integer>(); for(int i = 0 ; i < len ; i++){ map = new HashMap<Double ,Integer>(); int maxnum_curr = 0; int samenum = 1; Point currp = points[i]; for(int j = i+1 ; j < len ; j++){ double k = 0 ; if(points[j].x ==currp.x){ if(points[j].y==currp.y){ //两个点是同一个点 samenum++; continue; }else{//x坐标相等,斜率不存在 k = (double) Integer.MAX_VALUE; } }else{ k = (points[j].y-currp.y)/(double)(points[j].x-currp.x); if(k==-0.0 ) k = 0; } if(!map.containsKey(k)){ map.put(k,1); if(maxnum_curr<1) maxnum_curr = 1; }else{ int knum = map.get(k)+1; map.put(k,knum); if(knum>maxnum_curr) maxnum_curr = knum; } } maxnum_curr = maxnum_curr+samenum; if( maxnum_curr>maxnum) maxnum = maxnum_curr; } return maxnum; }